<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>${boot.version}</version>
</dependency>
spring:
#cache:
#缓存名称
#cache-names: guavaDemo
#缓存最大数量500条, 缓存失效时间 6个小时
#guava.spec: maximumSize=500,expireAfterWrite=360m
# REDIS (RedisProperties)
redis :
host : localhost # server host
port : 6379 # connection port
password : 123
pool.max-idle : 8 # pool settings ...
pool.min-idle : 1
pool.max-active : 8
pool.max-wait : -1
package com.ding.data.config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
@Configuration
public class CacheConfig implements ApplicationRunner {
@Resource
private List<CacheManager> cacheManagers;
public void run(ApplicationArguments args) throws Exception {
System.out.println("CacheManager大小为=========" + cacheManagers.size());
System.out.println("=================================================");
for(CacheManager c:cacheManagers){
System.out.println(c.getCacheNames());
}
}
@Bean(name = "redisCacheManager")
public RedisCacheManager redisCacheManager(
RedisTemplate<Object, Object> redisTemplate) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
RedisCacheManager redisCacheManager = new RedisCacheManager(
redisTemplate);
redisCacheManager.setCacheNames(Arrays.asList("redisDemo"));
redisCacheManager.setUsePrefix(true);
return redisCacheManager;
}
@Bean(name = "guavaCacheManager")
public GuavaCacheManager getGuavaCacheManager() {
GuavaCacheManager guavaCacheManager = new GuavaCacheManager();
guavaCacheManager.setCacheBuilder(CacheBuilder.newBuilder()
.expireAfterWrite(3600, TimeUnit.SECONDS).maximumSize(1000));
ArrayList<String> guavaCacheNames = Lists.newArrayList();
guavaCacheNames.add("guavaDemo");
guavaCacheManager.setCacheNames(guavaCacheNames);
return guavaCacheManager;
}
@Bean(name = "cacheManager")
@Primary
public CompositeCacheManager cacheManager(
RedisCacheManager redisCacheManager,
GuavaCacheManager guavaCacheManager) {
CompositeCacheManager cacheManager = new CompositeCacheManager(
redisCacheManager, guavaCacheManager);
return cacheManager;
}
}
ポイント4-グアバキャッシュ
package com.ding.data.cache;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
//@CacheConfig(cacheManager = "guavaCacheManager")
public class GuavaDataCache {
private Map<Long, String> dataMap = new HashMap<Long, String>();
/**
* 初始化
*/
@PostConstruct
public void init() {
dataMap.put(1L, "张三");
dataMap.put(2L, "李四");
dataMap.put(3L, "王五");
}
/**
* 查询
* 如果数据没有缓存,那么从dataMap里面获取,如果缓存了,
* 那么从guavaDemo里面获取
* 并且将缓存的数据存入到 guavaDemo里面
* 其中key 为 #id+dataMap
*/
@Cacheable(value="guavaDemo" ,key="#id + 'dataMap'")
public String query(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + " : query id is " + id);
return dataMap.get(id);
}
/**
* 插入 或者更新
* 插入或更新数据到dataMap中
* 并且缓存到 guavaDemo中
* 如果存在了那么更新缓存中的值
* 其中key 为 #id+dataMap
*/
@CachePut(value="guavaDemo" ,key="#id + 'dataMap'")
public String put(Long id, String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + " : add data ,id is "+ id);
dataMap.put(id, value);
// data persistence
return value;
}
/**
* 删除
* 删除dataMap里面的数据
* 并且删除缓存guavaDemo中的数据
* 其中key 为 #id+dataMap
*/
@CacheEvict(value="guavaDemo" , key="#id + 'dataMap'")
public void remove(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + " : remove id is "+ id + " data");
dataMap.remove(id);
// data remove
}
}
ポイント5-redisキャッシュ
package com.ding.data.cache;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
//@CacheConfig(cacheManager = "redisCacheManager")
public class RedisDataCache {
private Map<Long, String> dataMap = new HashMap<Long, String>();
/**
* 初始化
*/
@PostConstruct
public void init() {
dataMap.put(1L, "111");
dataMap.put(2L, "222");
dataMap.put(3L, "333");
}
/**
* 查询
* 如果数据没有缓存,那么从dataMap里面获取,如果缓存了,
* 那么从guavaDemo里面获取
* 并且将缓存的数据存入到 guavaDemo里面
* 其中key 为 #id+dataMap
*/
@Cacheable(value="redisDemo" ,key="#id + 'dataMap'")
public String query(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + " : query id is " + id);
return dataMap.get(id);
}
/**
* 插入 或者更新
* 插入或更新数据到dataMap中
* 并且缓存到 guavaDemo中
* 如果存在了那么更新缓存中的值
* 其中key 为 #id+dataMap
*/
@CachePut(value="redisDemo" ,key="#id + 'dataMap'")
public String put(Long id, String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + " : add data ,id is "+ id);
dataMap.put(id, value);
// data persistence
return value;
}
/**
* 删除
* 删除dataMap里面的数据
* 并且删除缓存guavaDemo中的数据
* 其中key 为 #id+dataMap
*/
@CacheEvict(value="redisDemo" , key="#id + 'dataMap'")
public void remove(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()) + " : remove id is "+ id + " data");
dataMap.remove(id);
// data remove
}
}
ポイント6-電話
package com.ding.data;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ding.data.cache.GuavaDataCache;
import com.ding.data.cache.RedisDataCache;
/**
* 是Spring Boot项目的核心注解,主要是开启自动配置
*/
@SpringBootApplication
// same as @Configuration @EnableAutoConfiguration @ComponentScan
@RestController
// 开启缓存
@EnableCaching
public class App {
@Autowired
private GuavaDataCache dataCache;
@Autowired
private RedisDataCache rdataCache;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@RequestMapping("/put")
public String put(Long id, String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date()) + " : value is "
+ dataCache.put(id, value);
}
@RequestMapping("/get")
public String query(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date()) + " : value is " + dataCache.query(id);
}
@RequestMapping("/remove")
public String remove(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dataCache.remove(id);
return sdf.format(new Date()) + " : success ";
}
@RequestMapping("/putr")
public String putr(Long id, String value) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date()) + " : value is "
+ rdataCache.put(id, value);
}
@RequestMapping("/getr")
public String queryr(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date()) + " : value is " + rdataCache.query(id);
}
@RequestMapping("/remover")
public String remover(Long id) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
rdataCache.remove(id);
return sdf.format(new Date()) + " : success ";
}
}
テスト1-redisに書き込みがあるかどうか-はい
RedisCacheアクセス
アクセス
http:// localhost:8080 / getr?id = 1
次のように、Redisサーバーを表示します
見える
/ getr?id = 1
このリンクが戻ると、データはRedisサーバーに書き込まれます。
テスト2--Guavaキャッシュアクセス
アクセス
http:// localhost:8080 / get?id = 1
次に、
http:// localhost:8080 / put?id = 1&value = 777777
Redisで値を確認してください。変更はありません。これは、redisキャッシュとguavaキャッシュが相互に干渉せず、期待どおりに正しくアクセスされていることを示しています。なんでそんなこと言うの?以前に他の構成を試したため、キャッシュが混乱していることが判明しましたが、現在は正常であり、現在の構成ファイルと関連する構成情報が正しく書き込まれていることを示しています。
★ポイント3の説明
プロジェクト開始時の印刷
以下は、プロジェクトの起動時に出力されます。ApplicationRunnerインターフェースの具体的な使用法はBaiduです。ApplicationRunnerインターフェースを実装する必要はありません。ここでは、起動時にCacheManagerを印刷して表示します。
図からわかるように、 @ Beanの 注釈が付けられた3つのCachaManagerがcacheManagerに追加されています。
CompositeCacheManager
Spring Cacheは、CacheManagerの下のキャッシュ名(cacheNames属性)を使用してキャッシュを区別できます。Spring Cacheは、すべてのCacheManagerをプロキシするCompositeCacheManagerを提供します。指定されたcacheNameに従ってすべてのCacheManagerをトラバースして、対応するキャッシュを見つけます。