如果對SpringBoot緩存不熟悉的建議先看第一片文章SpringBoot使用caffeine作為緩存,為什么使用分布式緩存?在實際開發(fā)場景中,往往單機應用無法滿足當前的需求润匙,需要對項目進行分布式部署,由此京痢,每個項目中的緩存都是屬于自己獨立服務的,并不能共享,其次逝嚎,當某個服務更新了緩存歇万,其他服務并不知道琳省,當用戶請求到其他服務時潜支,獲取到的往往還是舊的數(shù)據(jù)吨艇,說到這,就有人會說使用Redis進行代替郭厌,但是Redis畢竟是借助于第三方卸耘,會存在網(wǎng)絡消耗祠饺,如果所有都堆積到Redis硅堆,會造成Redis被大量并發(fā)訪問屿储,最壞會被宕機,所以我們可以使用本地緩存和Redis緩存結合進行使用渐逃,運用Redis的發(fā)布訂閱功能進行通知其他服務更新緩存.
接下來簡單介紹本人開源的一個分布式緩存使用方法
一. 引入依賴
<dependency>
<groupId>cn.gjing</groupId>
<artifactId>tools-cache</artifactId>
<version>1.0.0</version>
</dependency>
二. 啟動類標上注解
/**
* @author Gjing
*/
@SpringBootApplication
@EnableToolsCache
public class TestRedisApplication {
public static void main(String[] args) {
SpringApplication.run(TestRedisApplication.class, args);
}
}
三. 配置
1. 配置介紹
以下為所有配置信息, 使用時可自定義設置, 皆以tools.cache
開頭
配置項 | 描述 |
---|---|
cache-names | 緩存key名 |
cache-value-nullable | 是否存儲控制,默認true 民褂,防止緩存穿透 |
dynamic | 是否動態(tài)根據(jù)cacheName創(chuàng)建Cache實現(xiàn), 默認true
|
cache-prefix | 緩存key的前綴 |
caffeine.initial-capacity | 初始化大小 |
caffeine.expire-after-access | 訪問后過期時間茄菊,單位毫秒 |
caffeine.expire-after-write | 寫入后過期時間,單位毫秒 |
caffeine.maximum-size | 最大緩存對象個數(shù)赊堪,超過此數(shù)量時之前放入的緩存將失效 |
caffeine.refresh-after-write | 寫入后刷新時間面殖,單位毫秒 |
redis.every-cache-expire | 每個cacheName的過期時間,單位秒哭廉,優(yōu)先級比expire 高 |
redis.expire | 全局過期時間脊僚,單位秒,默認不過期 |
redis.topic | 緩存更新時通知其他節(jié)點的topic名稱 |
2. 配置示例
- yml方式
tools:
cache:
cache-prefix: 鎖的前綴
redis:
expire: 10
caffeine:
expire-after-write: 3000
- JavaBean方式
/**
* @author Gjing
**/
@Configuration
public class CacheConfiguration {
@Bean
public ToolsCache toolsCache() {
return ToolsCache.builder()
.cachePrefix("鎖的前綴")
.dynamic(true)
.build();
}
@Bean
public RedisCache redisCache() {
return RedisCache.builder()
.expire(10)
.build();
}
@Bean
public CaffeineCache caffeineCache() {
return CaffeineCache.builder()
.expireAfterWrite(3000)
.build();
}
}
三. 簡單使用
/**
* @author Gjing
**/
@Service
@Slf4j
public class CustomService {
@Resource
private CustomRepository customRepository;
/**
* 獲取一個用戶
* @param customId 用戶id
* @return Custom
*/
@Cacheable(value = "user",key = "#customId")
public Custom getCustom(Integer customId) {
log.warn("查詢數(shù)據(jù)庫用戶信息");
return customRepository.findById(customId).orElseThrow(() -> new NullPointerException("User is not exist"));
}
/**
* 刪除一個用戶
* @param customId 用戶id
*/
@CacheEvict(value = "user", key = "#customId")
public void deleteUser(Integer customId) {
Custom custom = customRepository.findById(customId).orElseThrow(() -> new NullPointerException("User is not exist"));
customRepository.delete(custom);
}
}
四. 定義接口調(diào)用
/**
* @author Gjing
**/
@RestController
public class CustomController {
@Resource
private CustomService customService;
@GetMapping("/user/{custom-id}")
@ApiOperation(value = "查詢用戶",httpMethod = "GET")
public ResponseEntity getUser(@PathVariable("custom-id") Integer customId) {
return ResponseEntity.ok(customService.getCustom(customId));
}
@DeleteMapping("/user")
@ApiOperation(value = "刪除用戶", httpMethod = "DELETE")
@ApiImplicitParam(name = "customId", value = "用戶Id", dataType = "int", required = true, paramType = "Query")
@NotNull
public ResponseEntity deleteUser(Integer customId) {
customService.deleteUser(customId);
return ResponseEntity.ok("Successfully delete");
}
}
調(diào)用結果
cache
使用中如果有任何問題,歡迎評論留言辽幌,我會及時回復以及更新增淹,源代碼地址:tools-redis