在程序开发中,经常会用到缓存,最常用的后端缓存技术有Redis、MongoDB、Memcache等。
而有时候我们希望能够手动清理缓存,点一下按钮就把当前Redis的缓存和前端缓存都清空。
功能非常简单,创建一个控制器类CacheController,并提供一个post请求的接口/cache/clean供用户使用。
目录
后端代码
CacheController.java
RedisUtils.java
StringRedisUtils.java
前端代码
后端代码
CacheController.java
import cn.edu.sgu.www.mhxysy.consts.MimeType;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.restful.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;/*** @author heyunlin* @version 1.0*/
@RestController
@Api(tags = "缓存管理")
@RequestMapping(path = "/cache", produces = MimeType.APPLICATION_JSON_CHARSET_UTF_8)
public class CacheController {/*** 应用名*/@Value("${spring.application.name}")private String service;private final RedisUtils redisUtils;@Autowiredpublic CacheController(RedisUtils redisUtils) {this.redisUtils = redisUtils;}@ApiOperation("清理应用的缓存")@RequestMapping(value = "/clean", method = RequestMethod.POST)public JsonResult<Void> location() {redisUtils.deleteByPattern(service + "*");return JsonResult.success("缓存清理成功~");}}
RedisUtils.java
RedisUtils是一个接口,它的实现类为StringRedisUtils是通过StringRedisTemplate封装成的工具类。
import java.util.concurrent.TimeUnit;/*** redis工具类* @author heyunlin* @version 1.0*/
public interface RedisUtils {/*** 获取key的值:get key* @param key redis的key* @return key的值*/String get(String key);/*** 设置key:set key value* @param key redis的key* @param value key的值*/void set(String key, String value);/*** 设置key:set key value ex timeout = set key value + expire key timeout* @param key redis的key* @param value key的值* @param timeout 过期时间* @param timeUnit 时间单位*/void set(String key, String value, long timeout, TimeUnit timeUnit);/*** 删除key:del key* @param key redis的key*/void delete(String key);/*** 根据pattern删除key:del keys pattern* @param pattern String*/void deleteByPattern(String pattern);/*** 让key自增:incrby key* @param key redis的key* @return 自增后的值*/Long incrBy(String key);/*** 判断key是否存在* @param key redis的key* @return key存在则返回true,否则返回false*/Boolean hasKey(String key);/*** 设置key的过期时间:expire key seconds* @param key redis的key* @param timeout 过期时间* @param timeUnit 时间单位*/void expire(String key, long timeout, TimeUnit timeUnit);
}
StringRedisUtils.java
import cn.edu.sgu.www.mhxysy.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.Set;
import java.util.concurrent.TimeUnit;/*** 封装了StringRedisTemplate的redis工具类* @author heyunlin* @version 1.0*/
@Component
public class StringRedisUtils implements RedisUtils {private final StringRedisTemplate stringRedisTemplate;@Autowiredpublic StringRedisUtils(StringRedisTemplate stringRedisTemplate) {this.stringRedisTemplate = stringRedisTemplate;}@Overridepublic String get(String key) {return getValueOperations().get(key);}@Overridepublic void set(String key, String value) {getValueOperations().set(key, value);}@Overridepublic void set(String key, String value, long timeout, TimeUnit timeUnit) {getValueOperations().set(key, value, timeout, timeUnit);}@Overridepublic void delete(String key) {stringRedisTemplate.delete(key);}@Overridepublic void deleteByPattern(String pattern) {Set<String> keys = stringRedisTemplate.keys(pattern);if (CollectionUtils.isNotEmpty(keys)) {stringRedisTemplate.delete(keys);}}@Overridepublic Long incrBy(String key) {return getValueOperations().increment(key);}@Overridepublic Boolean hasKey(String key) {return stringRedisTemplate.hasKey(key);}@Overridepublic void expire(String key, long timeout, TimeUnit timeUnit) {stringRedisTemplate.expire(key, timeout, timeUnit);}/*** 获取ValueOperations对象* @return ValueOperations<String, String>*/private ValueOperations<String, String> getValueOperations() {return stringRedisTemplate.opsForValue();}}
前端代码
点击下拉菜单的清理缓存按钮,就能完成删除前后端缓存的功能。
前端的javascript代码如下
/*** 封装的ajax post请求* @param url 请求url* @param params 请求参数* @param success 成功回调函数* @param error 失败回调函数* @param async 是否异步*/
function ajaxPost(url, params, success, error, async = true) {$.ajax({type: "POST",url: base + url,data: params,async: async,cache: false,dataType: "json",processData: true,success: success,error: error});
}/*** 错误回调函数* @param res*/
let error = (res) => {let response = res.responseJSON;// 请求有响应if (res && response) {let status = res.status;if (status) {let message;if (status === 404) { // 404 not foundif (response.path) {message = "路径" + response.path + "不存在。";} else {message = response.message;}} else {message = response.message;}alert(message);// console.log("响应状态码:" + status + ", 响应消息:" + message);} else {console.log("请求没有响应状态码~");}} else {console.log("请求无响应~");}
}$(function() {$("#clean").on("click", function() {ajaxPost("/cache/clean", {},function(response) {showMsg(response.message);localStorage.clear();}, error);});});
先通过post请求访问/cache/clean接口,当清理完后端的redis缓存数据之后,再清空前端localStorage的缓存,当然也可以清除cookile里的缓存数据。