前提:
環境: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);