栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

1.引言

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

2.整合redis

pom.xml:


    
      org.springframework.data
      spring-data-redis
      2.3.0.RELEASE
    
    
      redis.clients
      jedis
    

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自定义序列化内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号