本文jdk8
首先在pom中添加缓存有关的依赖:
<!--缓存配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--redis配置--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.5.RELEASE</version> </dependency>
添加配置文件,是redis缓存替换spring默认的缓存:
package com.bxw.configuration; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.core.RedisTemplate; @Configuration @EnableCaching public class RedisConfig { /** * 采用RedisCacheManager作为缓存管理器 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisTemplate redisTemplate){ return new RedisCacheManager(redisTemplate); } }
完成缓存service:
package com.bxw.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.Optional; import java.util.concurrent.TimeUnit; @Service public class RedisService { @Autowired private StringRedisTemplate stringRedisTemplate; public void setString(Optional<String> key, Optional<Object> value, Long time){ this.setObject(key,value,time); } private void setObject(Optional<String> key, Optional<Object> value, Long time){ if(key.isPresent() && value.isPresent()){ String key1 = key.get(); Object val1 = value.get(); if(val1 instanceof String){ String strVal = (String) val1; stringRedisTemplate.opsForValue().set(key1,strVal); if(time != null){ stringRedisTemplate.opsForValue().set(key1,strVal,time, TimeUnit.SECONDS); } return; } } } public String getValue(Optional<String> key){ if(key.isPresent()){ return stringRedisTemplate.opsForValue().get(key.get()); } return null; } }
控制层中调用:
//redis @GetMapping("/setString") @ResponseBody public String setString(String key,String value){ redisService.setString(Optional.of(key),Optional.of(value),null); return "success"; } @GetMapping("/getValue") @ResponseBody public String getValue(String key){ return redisService.getValue(Optional.of(key)); }