SpringBoot整合Redis的两种方式
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
配置redis连接
#配置Redis服务器属性
spring.redis.host=localhost
spring.redis.port=6379
#配置连接超时时间(毫秒)
spring.redis.timeout=3000
#配置连接池属性
#连接池最大的链接数
spring.redis.jedis.pool.max-active=20
#连接池的最大空闲链接
spring.redis.jedis.pool.max-idle=20
#连接池的最小空闲连接
spring.redis.jedis.pool.min-idle=5
#连接池的最大等待时间
spring.redis.jedis.pool.max-wait=3000
#缓存名称,一般会作为缓存在业务上的分类,以key的前缀出现(userCache::)
spring.cache.cache-names=userCache
#禁用缓存前缀
#spring.cache.redis.use-key-prefix=false
#缓存超时时间
spring.cache.redis.time-to-live=120000
1.开启使用缓存
@SpringBootApplication
@EnableCaching
public class DemoredisApplication {
public static void main(String[] args) {
SpringApplication.run(DemoredisApplication.class, args);
}
}
在service或者dao层中使用缓存
@Service
public class CacheServiceImpl implements CacheService {
@Resource
private UserMapper userMapper;
@Override
@CachePut(value = "userCache", key = "'user:' + #result.id")
public User saveUser(User user) {
return userMapper.adduser(user);
}
@Override
@Cacheable(value = "userCache", key = "'user:' + #id", unless = "#result == null")
public User getUser(Integer id) {
System.out.println("没有命中缓存,进入业务方法了");
return userMapper.findUserById(id);
}
@Override
@CachePut(value = "userCache", key = "'user:' + #result.id", condition = "#result != null")
public User updateUser(User user) {
User u = this.getUser(user.getId());
if (u == null) {
return null;
}
return userMapper.updateUser(user);
}
@Override
@CacheEvict(value = "userCache", key = "'user:' + #id", beforeInvocation = true)
public void removeUser(Integer id) {
userMapper.deleteUserById(id);
}
}
参考链接: https://segmentfault.com/a/1190000017057950.