1、配置文件加入配置
type: redis (用redis缓存)
cache-names: wasData (保存分组名称叫wasData )
spring:
cache:
type: redis
cache-names: wasData
redis:
host: 127.0.0.1
port: 6379
pool:
max-idle: 100
min-idle: 1
max-active: 1000
max-wait: -1
2、在启动类加上注解@EnableCaching
@SpringBootApplication
@EnableCaching
public class ProjectStartApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication app = new SpringApplication(ProjectStartApplication.class);
app.run(args);
}
}
3、控制类的接口上加上注解@Cacheable()
cacheNames = "wasData" 分组名称叫wasData,与配置文件对应
key = "#type != null ? #type : 'defaultKey'" 保存的key使用我的方法入参String type,写法为 @Cacheable(cacheNames = "分组名", key = #入参")
#type != null ? #type : 'defaultKey' 如果我的key没有传或者等null,使用默认生成的key
unless = "#result == null" 如果我的返回值为null,不进行缓存
@ResponseBody
@DZ_AuthPassport
@RequestMapping(value = "getWasData")
@Cacheable(cacheNames = "wasData", key = "#type != null ? #type : 'defaultKey'", unless = "#result == null")
public String getWasData(String type) {
JSONObject json = new JSONObject();
if (StringUtil.isBlankOrNull(type)) {
json.put("error", true);
return null;
}
json.put("type", type);
String url = "";
switch (type) {
case "ttlist": {
url = wasPrefix.getTtlist();
break;
}
case "xwdetail": {
url = wasPrefix.getXwdetail();
break;
}
}
if (StringUtil.isBlankOrNull(url)) {
return null;
}
String result = HttpClientUtils.sendHttpGet(url);
json.put("error", false);
json.put("data", result);
return json.toJSONString();
}
以上已经可以实现保存,测试接口
redis当中没有缓存时,断点到接口中是可以进入接口方法的。当第一次执行之后,生成缓存,第二次执行接口,没有进入方法,直接从缓存取数据返回
设置过期时间
package com.terton.api.config;
import org.springframework.cache.CacheManager;
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;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class CustomRedisCacheManager {
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//默认使用cacheNames作为key的前缀
rcm.setUsePrefix(true);
//设置缓存过期时间
Map<String, Long> expires = new HashMap<>();
expires.put("wasData", 30L);
// expires.put("1h", 3600 * 1L);
// expires.put("10m", 60 * 10L);
rcm.setExpires(expires);
// rcm.setDefaultExpiration(60 * 60 * 12);//默认过期时间
return rcm;
}
}
查看过期时间是否设置成功,如果没过期时间,值为-1