SpringBoot2.3整合redis缓存自定义序列化的实现
程序员文章站
2022-09-25 15:11:00
1.引言我们使用redis作为缓存中间件时,当我们第一次查询数据的时候,是去数据库查询,然后查到的数据封装到实体类中,实体类会被序列化存入缓存中,当第二次查数据时,会直接去缓存中查找被序列化的数据,然...
1.引言
我们使用redis作为缓存中间件时,当我们第一次查询数据的时候,是去数据库查询,然后查到的数据封装到实体类中,实体类会被序列化存入缓存中,当第二次查数据时,会直接去缓存中查找被序列化的数据,然后反序列化被我们获取。我们在缓存中看到的序列化数据不直观,如果想看到类似json的数据格式,就需要自定义序列化规则。
2.整合redis
pom.xml:
<!--引入redis--> <dependency> <groupid>org.springframework.data</groupid> <artifactid>spring-data-redis</artifactid> <version>2.3.0.release</version> </dependency> <dependency> <groupid>redis.clients</groupid> <artifactid>jedis</artifactid> </dependency>
application.yml:
spring: redis: host: 192.168.85.130 port: 6379 database: 0
springboot主配置类要加上@enablecaching注解
3.自定义序列化
@configuration public class myredisconfig { @bean public redistemplate<object, object> empredistemplate(redisconnectionfactory redisconnectionfactory)throws unknownhostexception { redistemplate<object,object> template = new redistemplate<>(); template.setconnectionfactory(redisconnectionfactory); jackson2jsonredisserializer<object> serializer = new jackson2jsonredisserializer<object>(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自定义序列化内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!