1. 程式人生 > 程式設計 >SpringBoot2.3整合redis快取自定義序列化的實現

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快取自定義序列化的實現的文章就介紹到這了,更多相關SpringBoot2.3 redis自定義序列化內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!