Spring Boot 整合 Redis
pom.xml
依赖:
<!-- redis依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
application.yml
配置
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: 5508769123data:#Redis 相关配置redis:host: localhostport: 6379 #Redis端口号,具体可在Redis的.conf文件中查看#password: 123456database: 0jedis:#Redis连接池配置pool:max-active: 8max-wait: 1msmax-idle: 4min-idle: 0cache:redis:time-to-live: 1800000 #设置缓存过期时间单位毫秒ms
- 在启动类上添加
@EnableCaching
注解
package com.mercurows;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication
@EnableCaching
public class SpringbootCacheDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootCacheDemoApplication.class, args);}
}
- 在需要的地方进行Cache缓存操作,这里在controller中(框架为springboot)
package com.mercurows.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mercurows.entity.User;
import com.mercurows.service.UserService;import lombok.extern.slf4j.Slf4j;@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {@Autowiredprivate CacheManager cacheManager;@Autowiredprivate UserService userService;/*** CahcePut:将方法返回值放入缓存* @Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。* value:缓存的名称,每个缓存名称下面可以有多个key* key:缓存的key*/@CachePut(value = "userCache",key = "#user.id")@PostMappingpublic User save(User user) {userService.save(user);return user;}/*** CacheEvict:清理指定缓存* value:缓存的名称,每个缓存名称下面可以有多个key,同时也是指定清理缓存的名称* key:缓存的key* allEntries:表明清理缓存时直接清理所有的*/@CacheEvict(value = "userCache", key = "#p0",allEntries = true)// @CacheEvict(value = "userCache",key = "#root.args[0]")// @CacheEvict(value = "userCache",key = "#id")@DeleteMapping("/{id}")public void delete(@PathVariable Long id) {userService.removeById(id);}// @CacheEvict(value = "userCache",key = "#p0.id")// @CacheEvict(value = "userCache",key = "#user.id")// @CacheEvict(value = "userCache",key = "#root.args[0].id")@CacheEvict(value = "userCache",key = "#result.id")@PutMappingpublic User update(User user) {userService.updateById(user);return user;}/*** Cacheable:在方法执行强spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据,* 若没有数据则将方法结果存入缓存、* value:缓存的名称,每个缓存名称下面可以有多个key* key:缓存的key* unless:满足条件则不缓存,即下次仍为null时还走查询而不是走缓存*/@Cacheable(value = "userCache", key = "#id",unless = "#result == null")@GetMapping("/{id}")public User getById(@PathVariable Long id) {User user = userService.getById(id);return user;}@Cacheable(value = "userCache",key = "#user.id+'_'+#user.name")@GetMapping("/list")public List<User> list(User user) {LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(user.getId() != null, User::getId, user.getId());queryWrapper.eq(user.getName() != null, User::getName, user.getName());List<User> list = userService.list(queryWrapper);return list;}
}
value
的作用就是给被缓存的方法起个名字,下次再请求这个方法的时候就知道去找那个缓存了。缓存的实际结果通常是根据方法的参数计算得到的。每个不同的参数组合可以产生不同的缓存结果。这些缓存结果通常是以键值对(key-value pairs)的形式存储的,其中键(key)是用于标识不同参数组合的唯一标识,而值(value)则是对应的方法执行结果。
当使用
value
属性来定义缓存名称时,通常是在缓存配置中将这个名称与具体的方法和其参数关联起来。在缓存中,会维护一个键值对的数据结构,其中键是由方法的参数组成的,而值是方法执行的结果。
- 引用:Spring缓存注解@Cacheable、@CacheEvict、@CachePut使用