在使用本地緩存的時候,可以很好解決分布式緩存的單點問題,是以一般本地緩存有ehcache,guava和Caffeine。
guava已經在Spring5種不支援了,通過sprinboot的自動配置可以看到沒有了guava。
現在将Caffeine的使用簡單描述如下:
第一步、引入依賴
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
第二步、設定CacheManager
package com.jd.ins.qsm.demo.web.commom.config;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.CacheManager;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Configuration
public class CacheConfig {
@Bean
public CacheManager caffeineCacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
List<CaffeineCache> caffeineCaches = new ArrayList<>();
caffeineCaches.add(new CaffeineCache("QSM",//緩存名,可以了解為一個緩存庫
Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)//失效政策,寫入10秒之後失效
.build()));
cacheManager.setCaches(caffeineCaches);
return cacheManager;
}
}
第三步,寫業務
service層
package com.jd.ins.qsm.demo.web.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class CaffeineService {
/**
* 查詢
* @param key 作為緩存裡面的key
* @return 回源方法,若緩存沒有值,則回源查詢
*/
@Cacheable(value = "QSM", key = "#key")
public String cacheQSM(String key) {
log.info("cacheQSM方法正在運作");
try {
log.info("查詢後端資料中");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//可以通路redis或者資料庫擷取真實值
return RandomStringUtils.randomNumeric(32);
}
@CachePut(value = "QSM", key = "#key")
public String cachePutQSM(String key) {
log.info("cachePutQSM方法正在運作");
return key;
}
}
controller層
package com.jd.ins.qsm.demo.web.controller;
import com.jd.ins.qsm.demo.web.service.impl.CaffeineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CaffeineController {
@Autowired
private CaffeineService caffeineService;
@GetMapping("/caffeine/select/{key}")
public String cacheQSM(@PathVariable String key) {
return caffeineService.cacheQSM(key);
}
@GetMapping("/caffeine/put/{key}")
public String cachePutQSM(@PathVariable String key) {
return caffeineService.cachePutQSM(key);
}
}
第四步調用
http://localhost:8080/caffeine/select/qsm01
會發現,第一次調用需要等5秒,接下來10秒都秒回。過了這10s,再次擷取再次等5s。
總結:多級緩存和redis叢集很好解決了大流量通路的非常有效的方法。
正在去往BAT的路上修行