SpringBoot使用Redis清除所有緩存實現(xiàn)方式
更新時間:2025年08月28日 10:00:45 作者:程序yang
文章介紹通過遍歷刪除Redis所有key的方法,推薦使用RedisTemplate的delete方法而非StringRedisTemplate,需確保緩存操作統(tǒng)一使用同類型模板,避免類型不匹配問題
實現(xiàn)思路
簡單描述一下,通過遍歷獲取所有Redis的key值
有兩種方式
分別是StringRedisTemplate的delete方法和RedisTemplate的delete方法。
這里我是調(diào)用RedisTemplate對象的delete方法進行刪除。
參考代碼:
package com.example.business.controller;
import com.example.business.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Set;
/**
* redis
*/
@Controller
@RequestMapping(value = "/redis")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
/**
* 清除所有緩存
*
* @return
*/
@ResponseBody
@RequestMapping(value = "/del-cache", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
public JsonResult delCache() {
boolean state = false;
Set<String> keys = redisTemplate.keys("*");
for (String key : keys) {
redisTemplate.delete(key);
state = true;
}
if (state) {
return JsonResult.success("清除緩存成功!");
} else {
return JsonResult.error("無緩存數(shù)據(jù)可清除!");
}
}
}
這里需要注意
使用RedisTemplate緩存時,確保你設置緩存時,也是使用RedisTemplate。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java使用StampedLock實現(xiàn)高效讀寫功能
StampedLock 是 Java 8 引入的高性能鎖,提供了三種鎖模式:寫鎖、悲觀讀鎖和樂觀讀鎖,與傳統(tǒng)的 ReentrantReadWriteLock 相比,StampedLock 更注重性能,特別適合讀多寫少的場景,所以本文給大家介紹了Java使用StampedLock實現(xiàn)高效讀寫功能,需要的朋友可以參考下2025-01-01
httpclient的disableConnectionState方法工作流程
這篇文章主要為大家介紹了httpclient的disableConnectionState方法工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

