安装Redis
引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加配置信息
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password: pass
timeout: 10000ms
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
配置类RedisConfig
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
缓存测试
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private SysUserService userService;
@GetMapping()
@Cacheable(value="user-key")
public SysUserDO getUser(Long id){
SysUserDO userDO = userService.getById(id);
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return userDO;
}
}
附