温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-13 11:23:43 来源:亿速云 阅读:418 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关实现SpringBoot2.3整合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缓存自定义序列化的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI