springboot使用redis缓存
这里只是一个简单的记录,并不会讲解知识点
添加redis的依赖
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--Jedis客户端驱动-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
然后再配置文件中配置如下信息
#--------------------------------------------------------------------------------------------------
#Redis配置
#配置连接池属性
spring.redis.jedis.pool.min-idle=5
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=2000
#配置Redis服务器属性
spring.redis.port=6379
spring.redis.host=127.0.0.1
#spring.redis.password=dcpnet
#Redis 连接超时时间,单位:毫秒
spring.redis.timeout=1000
spring.redis.lettuce.pool.max-active=50
spring.redis.lettuce.pool.max-idle=30
spring.redis.lettuce.pool.max-wait=2000ms
#缓存
spring.cache.type=redis
spring.cache.cache-names=redisCache
#禁用前缀
spring.cache.redis.use-key-prefix=false
#允许保存空值
spring.cache.redis.cache-null-values=true
#自定义前缀
#spring.cache.redis.key-prefix=
#定义超时时间,单位毫秒
spring.cache.redis.time-to-live=600000
启动EnableCaching
@SpringBootApplication(scanBasePackages = "dcpnet.springbootredistest")
@EntityScan(basePackages = "dcpnet.springbootredistest.pojo")
@MapperScan(basePackages = "dcpnet.springbootredistest.mapper")
@ComponentScan(basePackages = {"dcpnet.springbootredistest.service","dcpnet.springbootredistest.controller"})
@EnableCaching
public class SpringbootredistestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootredistestApplication.class, args);
}
在相关的业务逻辑类上配置相关信息
@Service("userService")
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
@Override
@Cacheable(key = "'user_id'+#id")
public User chaXunById(Integer id) {
return this.userMapper.chaXunById(id);
}
/**
* 通过ID删除对象
*
* @param id 主键
* @return Map
*/
@Override
@CacheEvict(key = "#id",beforeInvocation = false)
public Map<String,Object> shanChuById(Integer id){
this.userMapper.shanChuById(id);
Map<String,Object> map = ReturnMap.getMap(ReturnCode.CHENG_GONG,ReturnMsg.SHAN_CHU_CHENG_GONG);
return map;
}
}
查询的用@Cacheable,删除的用@CacheEvit,更新使用@CachePut
这里不讲原理,只是简单的使用。做一个记录