缓存是高并发系统的利器,可以大大减轻数据库压力,提高响应速度。
以下介绍在spring boot中使用redis来自定义缓存工具类
引入redis pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
缓存服务接口
package com.test.house.service;
import java.util.concurrent.TimeUnit;
/**
* 自定义缓存工具类
*/
public interface CacheService {
/**
* 设置缓存
* @param key 缓存key
* @param value 缓存值
* @param timeout 缓存过期时间
* @param timeUnit 缓存过期时间单位
*/
public void setCache(String key, String value, long timeout, TimeUnit timeUnit);
/**
* 获取缓存
* @param key 缓存key
* @return
*/
public String getCache(String key);
public <V,K> String getCache(K key,Closure<V,K> closure);
public <V,K> String getCache(K key,Closure<V,K> closure,long timeout,TimeUnit timeUnit);
/**
* 删除缓存
* @param key
*/
public void deleteCache(String key);
}
缓存服务实现
package com.test.house.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class CacheServiceImpl implements CacheService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private long timeout = 1L;
private TimeUnit timeUnit = TimeUnit.HOURS;
@Override
public void setCache(String key, String value, long timeout, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(key,value,timeout,timeUnit);
}
@Override
public String getCache(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public <V, K> String getCache(K key, Closure<V, K> closure) {
return doGetCache(key,closure,this.timeout,this.timeUnit);
}
@Override
public <V, K> String getCache(K key, Closure<V, K> closure, long timeout, TimeUnit timeUnit) {
return doGetCache(key,closure,timeout,timeUnit);
}
@Override
public void deleteCache(String key) {
stringRedisTemplate.delete(key);
}
private <K,V> String doGetCache(K key,Closure<V,K> closure,long timeout,TimeUnit timeUnit){
String ret = getCache(key.toString());
if(ret == null){
Object r = closure.execute(key);
setCache(key.toString(),r.toString(),timeout,timeUnit);
return r.toString();
}
return ret;
}
}
package com.test.house.service;
public interface Closure<O,I> {
public O execute(I input);
}
测试调用
package com.test.house.controller;
import com.test.house.service.CacheService;
import com.test.house.service.Closure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/house")
@RestController
public class HelloController {
@Autowired
private CacheService cacheService;
@RequestMapping("/getCache")
public String getCache(){
String cacheKey = "1001";
return cacheService.getCache(cacheKey, new Closure<String, String>() {
@Override
public String execute(String id) {
//执行你的业务逻辑
//userService.getById(id)
return "getCache";
}
});
}
}