1.配置pom文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
2.修改项目启动类,增加注解@EnableCaching,开启缓存功能
3.编写redis的配置
@Configuration @EnableSwagger2 @ServletComponentScan @ComponentScan(basePackages = "com.xx") public class MyWebConfig extends WebMvcConfigurerAdapter { @Bean public CacheManager cacheManager() { EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean(); cmfb.setConfigLocation(new ClassPathResource("ehcache.xml")); cmfb.setShared(true); return new EhCacheCacheManager(cmfb.getObject()); } /** * 采用RedisCacheManager作为缓存管理器 */ public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // 设置缓存的过期时间 Map<String, Long> cacheTimes = new HashMap<>(); cacheTimes.put("pemission-ROA", 3600 * 24 * 7L); cacheTimes.put("permission-Resource", 3600L); cacheTimes.put("permission-User", 600L); cacheManager.setExpires(cacheTimes); return cacheManager; } /** * RedisTemplate配置 */ @SuppressWarnings({"rawtypes", "unchecked"}) public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer);// 如果key是String,需要配置一下StringSerializer,不然key会乱码 template.afterPropertiesSet(); return template; } }
#redis spring.redis.database=1 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.pool.max-idle=5000 spring.redis.pool.min-idle=0 spring.redis.pool.max-active=5000 spring.redis.pool.max-wait=10000 spring.redis.timeout=600
4.使用@Cacheable注解就可以用了
@Cacheable(value = "book", key = "#name", unless = "#result == null")
public List<BookDTO> getBookCache(String name)
{
return this.getBook(name);
}
5.在本地启动redis
进入目录运行 redis-server.exe redis.windows.conf
6.启动项目,调用接口,查看redis缓存内容
结-redis基础
redis一共分为五种基本数据类型:String、Hash、List、Set、ZSet
String类型是包含很多种类型的特殊类型,并且是二进制安全的。比如序列化的对象进
行存储,比如一张图片进行二进制存储,比如一个简单的字符串,数值等等。
set和get方法:
设置值:set name bhz 取值 get name (说明 设置name多次会覆盖)
删除值:del name
使用setnx(not exist)
name 如果不存在进行设置,存在就不需要进行设置了,返回0
使用setex(expired)
setex color 10 red 设置color的有效期为10秒,10秒后返回nil(在redis里nil表示空)
使用setrange 替换字符串:
set email 174754613@qq.com
setrange email 10 ww (10表示从第几位开始替换,后面跟上替换的字符串)
具体参考 : http://www.runoob.com/redis/redis-lists.html
文章参考:https://www.cnblogs.com/gdpuzxs/p/7222309.html