欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot2.3整合redis緩存自定義序列化的實現(xiàn)

 更新時間:2020年08月12日 11:13:14   作者:xhnb  
這篇文章主要介紹了SpringBoot2.3整合redis緩存自定義序列化的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

1.引言

我們使用redis作為緩存中間件時,當我們第一次查詢數(shù)據(jù)的時候,是去數(shù)據(jù)庫查詢,然后查到的數(shù)據(jù)封裝到實體類中,實體類會被序列化存入緩存中,當?shù)诙尾閿?shù)據(jù)時,會直接去緩存中查找被序列化的數(shù)據(jù),然后反序列化被我們獲取。我們在緩存中看到的序列化數(shù)據(jù)不直觀,如果想看到類似json的數(shù)據(jù)格式,就需要自定義序列化規(guī)則。

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”) :該注解在方法上,方法傳入?yún)?shù)默認為key值,方法返回值為value值,注解的參數(shù)value = "dept"是緩存的名子

結(jié)果:

到此這篇關(guān)于SpringBoot2.3整合redis緩存自定義序列化的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot2.3 redis自定義序列化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論