在程序開發中,經常會用到緩存,最常用的后端緩存技術有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里的緩存數據。