本文實例講述了spring boot注解方式使用redis緩存操作。分享給大家供大家參考,具體如下:
引入依賴庫
在pom中引入依賴庫,如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
注解使用
@Cacheable @Cacheable("product") @Cacheable(value = {"product","order"}, key = "#root.targetClass+'-'+#id") @Cacheable(value = "product", key = "#root.targetClass+'-'+#id")
自定義cacheManager
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id” cacheManager="cacheManager") @CachePut
應用到寫數據的方法上,如新增/修改方法
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id") @CacheEvict
即應用到移除數據的方法上,如刪除方法
@CacheEvict(value = "product", key = "#root.targetClass+'-'+#id")
提供的SpEL上下文數據
Spring Cache提供了一些供我們使用的SpEL上下文數據,下表直接摘自Spring官方文檔:
名字 | 位置 | 描述 | 示例 |
---|---|---|---|
methodName | root對象 | 當前被調用的方法名 | #root.methodName |
method | root對象 | 當前被調用的方法 | #root.method.name |
target | root對象 | 當前被調用的目標對象 | #root.target |
targetClass | root對象 | 當前被調用的目標對象類 | #root.targetClass |
args | root對象 | 當前被調用的方法的參數列表 | #root.args[0] |
caches | root對象 | 當前方法調用使用的緩存列表(如@Cacheable(value={"cache1", "cache2"})),則有兩個cache | #root.caches[0].name |
argument name | 執行上下文 | 當前被調用的方法的參數,如findById(Long id),我們可以通過#id拿到參數 | #user.id |
result | 執行上下文 | 方法執行后的返回值(僅當方法執行之后的判斷有效,如‘unless','cache evict'的beforeInvocation=false) | #result |
自定義Cache配置
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { /** * 自定義redis key值生成策略 */ @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); }; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(Object
更多關于java相關內容感興趣的讀者可查看本站專題:《Spring框架入門與進階教程》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。