Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29906
  • 博文数量: 10
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 90
  • 用 户 组: 普通用户
  • 注册时间: 2020-06-29 11:21
文章分类
文章存档

2020年(10)

我的朋友

分类: 项目管理

2020-07-02 15:29:47

org.springframework.boot

spring-boot-starter-data-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 implements DeptService {

@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 添加


阅读(1436) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~