<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;
}
}
Punto 4-caché de guayaba
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
}
}
Punto 5-redis caché
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
}
}
Punto 6-llamada
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 ";
}
}
Prueba 1-si hay escritura en redis-sí
Acceso a RedisCache
acceso
http: // localhost: 8080 / getr? id = 1
Ver el servidor Redis, de la siguiente manera
visible
/ getr? id = 1
Cuando este enlace regresa, los datos se escriben en el servidor de Redis.
Prueba 2: acceso a la caché de guayaba
acceso
http: // localhost: 8080 / get? id = 1
Luego llame
http: // localhost: 8080 / put? id = 1 & value = 777777
Verifique el valor en Redis, no hay cambios. Muestra que el caché de redis y el caché de guayaba no interfieren entre sí, y se accede a ellos correctamente como se esperaba. ¿Por qué dices eso? Como probé otras configuraciones antes, resultó que el caché estaba dañado, pero ahora es normal, lo que indica que los archivos de configuración actuales y la información de configuración relacionada están escritos correctamente.
★ Explicación del punto 3
Imprimir durante el inicio del proyecto
Lo siguiente se imprime durante el inicio del proyecto. El uso específico de la interfaz ApplicationRunner puede ser Baidu. No es necesario implementar la interfaz ApplicationRunner, aquí es para imprimir y mostrar el CacheManager al inicio.
Se puede ver en la figura @Bean anotado que se agregan tres CachaManager en los cacheManagers.
CompositeCacheManager
Spring Cache puede usar el nombre de la caché (atributo cacheNames) en CacheManager para distinguir la caché. Spring Cache proporciona CompositeCacheManager para proxy todos los CacheManagers. Recorra todos los CacheManagers de acuerdo con el cacheName especificado para encontrar el caché correspondiente.