• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot2.3整合redis缓存自定义序列化的实现

springboot 搞代码 4年前 (2022-01-05) 30次浏览 已收录 0个评论

这篇文章主要介绍了SpringBoot2.3整合redis缓存自定义序列化的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.引言

我们使用redis作为缓存中间件时,当我们第一次查询数据的时候,是去数据库查询,然后查到的数据封装到实体类中,实体类会被序列化存入缓存中,当第二次查数据时,会直接去缓存中查找被序列化的数据,然后反序列化被我们获取。我们在缓存中看到的序列化数据不直观,如果想看到类似json的数据格式,就需要自定义序列化规则。

2.整合redis

pom.xml:

 <!--引入redis--> org.springframework.dataspring-data-redis2.3.0.RELEASE redis.clientsjedis

application.yml:

 spring: redis: host: 192.168.85.130 port: 6379 database: 0 

springboot主配置类要加上@EnableCaching注解

3.自定义序列化

 @Configuration public class MyRedisConfig { @Bean public RedisTemplate empRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); template.setDefaultSerializer(serializer); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory){ RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofDays(1)) .disableCachingNullValues() .serializeKeysWith(RedisSerializationContext.SerializationPair .fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();} } 

4.测试

DeptService:

 @Service public class DeptService { @Autowired DepartmentMapper departmentMapper; @Cacheable(value = "dept") public Department findById(Integer id){ System.out.println("查询"+id+"号部门"); Department department = departmentMapper.getDeptById(id); return department; } } 

EmployeeService:

 @Service public class EmployeeService { @Autowired EmployeeMapper employeeMapper; @Cacheable(value = "emp") public Employee findById(Integer id){ System.out.println("查询"+id+"号员工"); Employee employee = employeeMapper.getEmpById(id); return employee; } } 

@Cacheable(value = “dept”) :该注解在方法上,方法传入参数默认为key值,方法返回值为value值,注解的参数value = “dept”是缓存的名子

结果:

到此这篇关于SpringBoot2.3整合redis缓存自定义序列化的实现的文章就介绍到这了,更多相关SpringBoot2.3 redis自定义序列化内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是SpringBoo来源gao.dai.ma.com搞@代*码网t2.3整合redis缓存自定义序列化的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot2.3整合redis缓存自定义序列化的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址