Spring Boot 入门之缓存和 NoSQL 篇(四)

本文介绍如何在SpringBoot项目中整合缓存技术EhCache和Redis,以及NoSQL数据库MongoDB,通过示例代码展示了不同场景下的配置与使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:Spring Boot 入门之缓存和 NoSQL 篇(四)
博客地址:http://www.extlight.com

一、前言

当系统的访问量增大时,相应的数据库的性能就逐渐下降。但是,大多数请求都是在重复的获取相同的数据,如果使用缓存,将结果数据放入其中可以很大程度上减轻数据库的负担,提升系统的响应速度。

本篇将介绍 Spring Boot 中缓存和 NoSQL 的使用。上篇文章《Spring Boot 入门之持久层篇(三)》

二、整合缓存

Spring Boot 针对不同的缓存技术实现了不同的封装,本篇主要介绍 EhCache 和 Redis 缓存。

Spring Boot 提供了以下几个注解实现声明式缓存:

注解说明
@EnableCaching开启缓存功能,放在配置类或启动类上
@CacheConfig缓存配置,设置缓存名称
@Cacheable执行方法前先查询缓存是否有数据。有则直接返回缓存数据;否则查询数据再将数据放入缓存
@CachePut执行新增或更新方法后,将数据放入缓存中
@CacheEvict清除缓存
@Caching将多个缓存操作重新组合到一个方法中

2.1 EhCache 缓存

2.1.1 添加依赖

 
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>
  5.  
  6. <dependency>
  7. <groupId>net.sf.ehcache</groupId>
  8. <artifactId>ehcache</artifactId>
  9. </dependency>

2.1.2 添加配置

1)在 src/main/resources 目录下创建 ehcache.xml 文件,内容如下:

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
  4.  
  5. <!-- 磁盘缓存位置 -->
  6. <diskStore path="java.io.tmpdir/ehcache"/>
  7.  
  8. <!-- 默认缓存 -->
  9. <defaultCache
  10. maxEntriesLocalHeap="10000"
  11. eternal="false"
  12. timeToIdleSeconds="120"
  13. timeToLiveSeconds="120"
  14. maxEntriesLocalDisk="10000000"
  15. diskExpiryThreadIntervalSeconds="120"
  16. memoryStoreEvictionPolicy="LRU">
  17. <persistence strategy="localTempSwap"/>
  18. </defaultCache>
  19.  
  20. <!-- 自定义缓存 -->
  21. <cache name="department"
  22. maxElementsInMemory="1000"
  23. eternal="false"
  24. timeToIdleSeconds="50"
  25. timeToLiveSeconds="50"
  26. overflowToDisk="false"
  27. memoryStoreEvictionPolicy="LRU"/>
  28. </ehcache>

说明:

 
  1. name:Cache 的唯一标识
  2. maxElementsInMemory:内存中允许存储的最大的元素个数
  3. maxElementsOnDisk:硬盘最大缓存个数,0代表无限个
  4. clearOnFlush:内存数量最大时是否清除
  5. eternal:缓存对象是否永久有效,如果是,超时设置将被忽略
  6. overflowToDisk:内存不足(超过 maxElementsInMemory)时,是否启用磁盘缓存
  7. timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
  8. timeToLiveSeconds:缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间
  9. diskPersistent:是否将缓存数据持久化到磁盘上,如果为 true,JVM 重启数据依然存在。默认值是false
  10. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
  11. diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
  12. memoryStoreEvictionPolicy:当达到 maxElementsInMemory 限制时,Ehcache 将根据指定策略清除内存。默认为 LRU(最近最少使用),其他策略有 FIFO(先进先出),LFU(较少使用)

2)application.properties :

 
  1. # 缓存类型(ehcache、redis)
  2. spring.cache.type=ehcache
  3.  
  4. # ehcache 配置文件
  5. spring.cache.ehcache.config=classpath:ehcache.xml
  6.  
  7. # 打印日志,查看 sql
  8. logging.level.com.light.springboot=DEBUG

2.1.3 编码

在持久层篇的基础上,结合 Mybatis 测试:

Service 层:

 
  1. @CacheConfig(cacheNames = "department")
  2. @Service
  3. public class DepartmentService {
  4.  
  5. @Autowired
  6. private DepartmentMapper departmentMapper;
  7.  
  8. @CachePut(key = "#department.id")
  9. public Department save(Department department) {
  10. System.out.println("保存 id=" + department.getId() + " 的数据");
  11. this.departmentMapper.insert(department);
  12. return department;
  13. }
  14.  
  15. @CachePut(key = "#department.id")
  16. public Department update(Department department) {
  17. System.out.println("修改 id=" + department.getId() + " 的数据");
  18. this.departmentMapper.update(department);
  19. return department;
  20. }
  21.  
  22. @Cacheable(key = "#id")
  23. public Department getDepartmentById(Integer id) {
  24. System.out.println("获取 id=" + id + " 的数据");
  25. Department department = this.departmentMapper.getById(id);
  26. return department;
  27. }
  28.  
  29. @CacheEvict(key = "#id")
  30. public void delete(Integer id) {
  31. System.out.println("删除 id=" + id + " 的数据");
  32. this.departmentMapper.deleteById(id);
  33. }
  34. }

控制层:

 
  1. @Controller
  2. @RequestMapping("department")
  3. @ResponseBody
  4. public class DepartmentController {
  5.  
  6. @Autowired
  7. private DepartmentService departmentService;
  8.  
  9. @RequestMapping("save")
  10. public Map<String,Object> save(Department department) {
  11. this.departmentService.save(department);
  12.  
  13. Map<String,Object> map = new HashMap<String,Object>();
  14. map.put("code", "200");
  15. map.put("msg", "保存成功");
  16. return map;
  17. }
  18.  
  19. @RequestMapping("get/{id}")
  20. public Map<String,Object> get(@PathVariable("id") Integer id) {
  21. Department department = this.departmentService.getDepartmentById(id);
  22.  
  23. Map<String,Object> map = new HashMap<String,Object>();
  24. map.put("code", "200");
  25. map.put("msg", "获取成功");
  26. map.put("data", department);
  27. return map;
  28. }
  29.  
  30. @RequestMapping("update")
  31. public Map<String,Object> update(Department department) {
  32. this.departmentService.update(department);
  33.  
  34. Map<String,Object> map = new HashMap<String,Object>();
  35. map.put("code", "200");
  36. map.put("msg", "修改成功");
  37. return map;
  38. }
  39.  
  40. @RequestMapping("delete/{id}")
  41. public Map<String,Object> delete(@PathVariable("id") Integer id) {
  42. this.departmentService.delete(id);
  43.  
  44. Map<String,Object> map = new HashMap<String,Object>();
  45. map.put("code", "200");
  46. map.put("msg", "删除成功");
  47. return map;
  48. }
  49. }

启动类:

添加 @EnableCaching 注解,开启缓存功能。

 
  1. @EnableCaching
  2. @SpringBootApplication
  3. public class SpringbootNosqlApplication {
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(SpringbootNosqlApplication.class, args);
  7. }
  8. }

2.1.4 测试说明

1) 发起保存请求:

 
  1. 保存 id=2 的数据
  2. 2017-12-06 14:50:48.800 DEBUG 680 --- [nio-8081-exec-7] c.l.s.dao.DepartmentMapper.insert : ==> Preparing: insert into department(id,name,descr) values(?,?,?)
  3. 2017-12-06 14:50:48.801 DEBUG 680 --- [nio-8081-exec-7] c.l.s.dao.DepartmentMapper.insert : ==> Parameters: 2(Integer), Ehcache 部门(String), Ehcache(String)
  4. 2017-12-06 14:50:48.868 DEBUG 680 --- [nio-8081-exec-7] c.l.s.dao.DepartmentMapper.insert : <== Updates: 1

2) 保存成功后,立刻发起查询请求,没有日志打印,但返回对象数据,说明数据是从缓存中获取。

3) 发起修改请求:

 
  1. 修改 id=2 的数据
  2. 2017-12-06 14:51:16.588 DEBUG 680 --- [nio-8081-exec-8] c.l.s.dao.DepartmentMapper.update : ==> Preparing: update department set name = ? , descr = ? where id = ?
  3. 2017-12-06 14:51:16.589 DEBUG 680 --- [nio-8081-exec-8] c.l.s.dao.DepartmentMapper.update : ==> Parameters: Ehcache 部门2(String), Ehcache2(String), 2(Integer)
  4. 2017-12-06 14:51:16.657 DEBUG 680 --- [nio-8081-exec-8] c.l.s.dao.DepartmentMapper.update : <== Updates: 1

4) 修改成功后,立刻发起查询请求,没有日志打印,但返回修改后的对象数据,说明缓存中的数据已经同步。

5) 发起删除请求:

 
  1. 删除 id=2 的数据
  2. 2017-12-06 14:52:07.572 DEBUG 680 --- [nio-8081-exec-1] c.l.s.dao.DepartmentMapper.deleteById : ==> Preparing: delete from department where id = ?
  3. 2017-12-06 14:52:07.572 DEBUG 680 --- [nio-8081-exec-1] c.l.s.dao.DepartmentMapper.deleteById : ==> Parameters: 2(Integer)
  4. 2017-12-06 14:52:07.613 DEBUG 680 --- [nio-8081-exec-1] c.l.s.dao.DepartmentMapper.deleteById : <== Updates: 1

6) 删除成功后,立刻发起查询请求,控制台打印 sql 语句,说明缓存数据被删除,需要查询数据库。

 
  1. 获取 id=2 的数据
  2. 2017-12-06 14:52:40.324 DEBUG 680 --- [nio-8081-exec-3] c.l.s.dao.DepartmentMapper.getById : ==> Preparing: select id,name,descr from department where id = ?
  3. 2017-12-06 14:52:40.325 DEBUG 680 --- [nio-8081-exec-3] c.l.s.dao.DepartmentMapper.getById : ==> Parameters: 2(Integer)
  4. 2017-12-06 14:52:40.328 DEBUG 680 --- [nio-8081-exec-3] c.l.s.dao.DepartmentMapper.getById : <== Total: 0

2.2 Redis 缓存

2.2.1 添加依赖

 
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

2.2.2 添加配置

application.properties :

 
  1. # redis 配置
  2. spring.redis.host=192.168.2.11
  3. spring.redis.port=6379
  4. spring.redis.password=redis123
  5. # 缓存过期时间,单位毫秒
  6. spring.cache.redis.time-to-live=60000
  7.  
  8. # 缓存类型(ehcache、redis)
  9. spring.cache.type=redis
  10.  
  11. # 打印日志,查看 sql
  12. logging.level.com.light.springboot=DEBUG

注意:spring.cache.type=redis,缓存类型设置成 redis。

完成上边 2 个步骤后,其他步骤与测试 Ehcache 时的步骤一致。

测试结果也一致,此处省略。

三、整合 Redis

上一个小节其实已经介绍了 Spring Boot 整合 Redis 的内容。

在添加 redis 依赖包启动项目后,Spring Boot 会自动配置 RedisCacheManger 和 RedisTemplate 的 Bean。如果开发者不想使用 Spring Boot 写好的 Redis 缓存,而是想使用其 API 自己实现缓存功能、消息队列或分布式锁之类的需求时,可以继续往下浏览。

Spring Data Redis 为我们提供 RedisTemplate 和 StringRedisTemplate 两个模板进行数据操作,它们主要 的访问方法如下:

方法说明
opsForValue()操作简单属性的数据
opsForList()操作含有 list 的数据
opsForSet()操作含有 set 的数据
opsForZSet()操作含有 zset 的数据
opsForHash()操作含有 hash 的数据

3.1 添加依赖

 
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

3.2 配置连接

 
  1. spring.redis.host=192.168.2.11
  2. spring.redis.port=6379
  3. spring.redis.password=redis123

3.3 编码

 
  1. @Component
  2. public class RedisDao {
  3.  
  4. @Autowired
  5. private StringRedisTemplate stringRedisTemplate;
  6.  
  7. public void set(String key, String value) {
  8. this.stringRedisTemplate.opsForValue().set(key, value);
  9. }
  10.  
  11. public String get(String key) {
  12. return this.stringRedisTemplate.opsForValue().get(key);
  13. }
  14.  
  15. public void delete(String key) {
  16. this.stringRedisTemplate.delete(key);
  17. }
  18. }

3.4 测试

 
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class RedisDaoTest {
  4.  
  5. @Autowired
  6. private RedisDao redisDao;
  7.  
  8. @Test
  9. public void testSet() {
  10. String key = "name";
  11. String value = "zhangsan";
  12.  
  13. this.redisDao.set(key, value);
  14. }
  15.  
  16. @Test
  17. public void testGet() {
  18. String key = "name";
  19. String value = this.redisDao.get(key);
  20. System.out.println(value);
  21. }
  22.  
  23. @Test
  24. public void testDelete() {
  25. String key = "name";
  26. this.redisDao.delete(key);
  27. }
  28. }

测试结果省略...

四、整合 MongoDB

Spring Data MongoDB 提供了 MongoTemplate 模板 和 Repository 让开发者进行数据访问。

4.1 添加依赖

 
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  4. </dependency>

4.2 配置连接

 
  1. spring.data.mongodb.host=192.168.2.31
  2. spring.data.mongodb.port=27017
  3. spring.data.mongodb.database=test

4.3 编码

4.3.1 使用 MongoTemplate

 
  1. @Component
  2. public class MongodbDao {
  3.  
  4. @Autowired
  5. private MongoTemplate mongoTemplate;
  6.  
  7. public void insert(Department department) {
  8. this.mongoTemplate.insert(department);
  9. }
  10.  
  11. public void deleteById(int id) {
  12. Criteria criteria = Criteria.where("id").is(id);
  13. Query query = new Query(criteria);
  14. this.mongoTemplate.remove(query, Department.class);
  15. }
  16.  
  17. public void update(Department department) {
  18. Criteria criteria = Criteria.where("id").is(department.getId());
  19. Query query = new Query(criteria);
  20. Update update = new Update();
  21. update.set("descr", department.getDescr());
  22. this.mongoTemplate.updateMulti(query, update, Department.class);
  23. }
  24.  
  25. public Department getById(int id) {
  26. Criteria criteria = Criteria.where("id").is(id);
  27. Query query = new Query(criteria);
  28. return this.mongoTemplate.findOne(query, Department.class);
  29. }
  30.  
  31. public List<Department> getAll() {
  32. List<Department> userList = this.mongoTemplate.findAll(Department.class);
  33. return userList;
  34. }
  35.  
  36. }

4.3.2 使用 Repository

  1. public interface DepartmentRepository extends MongoRepository<Department, Integer> {
  2.  
  3.  
  4. }

测试方式与 Redis 测试大同小异,测试结果省略...

五、源码下载

六、参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值