分类: Java
2020-05-29 16:51:41
原文地址:springboot使用redis做缓存 作者:专注的阿熊
依赖
application.yml配置
redis:
host: 121.89.192.157
port: 6379
jedis:
pool:
max-active: 25
max-idle: 20
min-idle: 10
password: ******
更改Java对象序列化方式
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
/**
* @Author: 软件171 邱忠玉 201707163
* @Date: 2020/3/19 16:19
* 指定redis序列化的方式
*/
@Configuration
public class RedisConfig {
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
RedisCacheConfiguration config = RedisCacheConfiguration
.defaultCacheConfig();
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
//把默认的jdk的序列化方式变成jackson
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
使用示例
@Service
public class DeptServiceImpl extends ServiceImpl
@Autowired
private DeptMapper deptMapper;
/**
* 添加部门
*/
@Override
@CachePut(cacheNames = "com.qzy.system.service.impl.DeptServiceImpl", key = "#result.id")
public Dept saveDept(Dept dept) {
//mp插入之后会自动回填
this.deptMapper.insert(dept);
return dept;
}
/**
* 修改部门
*/
@Override
@CachePut(cacheNames = "com.qzy.system.service.impl.DeptServiceImpl", key = "#result.id")
public Dept updateDept(Dept dept) {
this.deptMapper.updateById(dept);
return this.deptMapper.selectById(dept.getId());
}
/**
* 根据id查询一个部门对象
*/
@Override
@Cacheable(cacheNames = "com.qzy.system.service.impl.DeptServiceImpl", key = "#id")
public Dept getById(Serializable id) {
return super.getById(id);
}
/**
* 删除部门
*/
@Override
@CacheEvict(cacheNames = "com.qzy.system.service.impl.DeptServiceImpl", key = "#id")
public boolean removeById(Serializable id) {
return super.removeById(id);
}
}
关于注解
@EnableCaching 在启动类上加上注解启动缓存
#作用在你要缓存的数据上
@Cacheable(key="#id",cacheNames="com.sxt.service.impl.MenuServiceImpl") 查询
@Cacheput 添加