redis-对象的存储-JSON


前提:

环境:SpringBoot2.0以上版本,1.0版本重写缓存管理器的方式不同

1.存储的对象实现序列化

public class Employee implements Serializable {
}

2.导入redis包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.10.RELEASE</version>
        </dependency>

使用注解时:

修改默认配置

@Configuration
public class MyRedisConfig { 

     /* 缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //设置CacheManager的值序列化方式为json序列化
        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(jsonSerializer);
        RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(pair);
        //设置默认超过期时间是30秒
        defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
        //初始化RedisCacheManager
        return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
    }
}

实现

Controller层

  @GetMapping("/emp/{id}")
    public Employee getEmployee(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return employee;
    }

Srevice层

    @Cacheable(cacheNames = "emp",condition = "#id>0",unless="#result == null")
    public Employee getEmp(Integer id){ 
        Employee emp = employeeMapper.getEmpById(id);  
        return emp;
    }

 修改配置前

 

 修改配后--为JSON串

 

 

不使用注解时:

方式一:按照默认的序列化存储

@SpringBootTest
class Springboot01CacheApplicationTests {

    @Autowired
    EmployeeMapper employeeMapper;
 
    @Autowired
    RedisTemplate redisTemplate; //操作k-v都是对象

    @Test
    public void test(){
        Employee empById = employeeMapper.getEmpById(1);
        //默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中,
        //默认用的是jdk的序列化容器
        redisTemplate.opsForValue().set("emp-01", empById);
    }

}

方式二:将对象转换为JSON

一:将默认的JDK序列化机制修改为JSON

配置:

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
        template.setDefaultSerializer(ser);
        return template;
    }
}

实现:

@SpringBootTest
class Springboot01CacheApplicationTests {

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;//操作k-v都是字符串的

    @Autowired
    RedisTemplate redisTemplate; //操作k-v都是对象

    @Test
    public void test02(){
        Employee empById = employeeMapper.getEmpById(1);
  
        redisTemplate.opsForValue().set("emp-04", empById);

    }

}

二:手动将对象修改为JSON字符串

方式一:

JSONObject json = JSONObject.fromObject(stu);//将对象转换为JSON对象
String strJson=json.toString();//将JSON转换为字符串

方式二:

ObjectMapper mapper = new ObjectMapper();/*ObjectMapper是Jackson提供的一个类,作用是将java对象与json格式相互转化*/
jsonString = mapper.writeValueAsString(areaList);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM