天天看點

SpringBoot使用分布式緩存

如果對SpringBoot緩存不熟悉的建議先看第一片文章 SpringBoot使用caffeine作為緩存 ,為什麼使用分布式緩存?在實際開發場景中,往往單機應用無法滿足目前的需求,需要對項目進行分布式部署,由此,每個項目中的緩存都是屬于自己獨立服務的,并不能共享,其次,當某個服務更新了緩存,其他服務并不知道,當使用者請求到其他服務時,擷取到的往往還是舊的資料,說到這,就有人會說使用Redis進行代替,但是Redis畢竟是借助于第三方,會存在網絡消耗,如果所有都堆積到Redis,會造成Redis被大量并發通路,最壞會被當機,是以我們可以使用本地緩存和Redis緩存結合進行使用,運用Redis的釋出訂閱功能進行通知其他服務更新緩存.

接下來簡單介紹本人開源的一個分布式緩存使用方法

一. 引入依賴

<dependency>
    <groupId>cn.gjing</groupId>
    <artifactId>tools-redis</artifactId>
    <version>1.2.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 是否動态根據cacheName建立Cache實作, 預設

true

cache-prefix 緩存key的字首
caffeine.initial-capacity 初始化大小
caffeine.expire-after-access 通路後過期時間,機關毫秒
caffeine.expire-after-write 寫入後過期時間,機關毫秒
caffeine.maximum-size 最大緩存對象個數,超過此數量時之前放入的緩存将失效
caffeine.refresh-after-write 寫入後重新整理時間,機關毫秒
redis.every-cache-expire 每個cacheName的過期時間,機關秒,優先級比

expire

redis.expire 全局過期時間,機關秒,預設不過期
redis.topic 緩存更新時通知其他節點的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("查詢資料庫使用者資訊");
        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);
    }
}           

四. 定義接口調用

/**
 * @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");
    }
}           

調用結果

SpringBoot使用分布式緩存

使用中如果有任何問題,歡迎評論留言,我會及時回複以及更新,源代碼位址:

tools-redis