一 引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
二 添加配置文件(application.properties中添加redis的配置属性)
#=========# REDIS #========== # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=10.20.3.150 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0
三 编写redis配置类
package com.study.springboot.SpringBoot_A.cache; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; /** * @author 赵超 * @Description Redis 配置类 * @create 2018-03-23 16:06 **/ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { // 缓存数据时Key的生成器,可以依据业务和技术场景自行定制 @Bean public KeyGenerator keyGenerator() { /*return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } };*/ return (target, method, params) -> { StringBuffer sb = new StringBuffer(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object o : params) { sb.append(o.toString()); } return sb.toString(); }; } // 定制缓存管理器的属性,默认提供的CacheManager对象可能不能满足需要 // 因此建议依赖业务和技术上的需求,自行做一些扩展和定制 @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 rcm.setDefaultExpiration(60);//秒 return rcm; } @Bean 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); template.afterPropertiesSet(); return template; } }
四 测试使用
package com.study.springboot.SpringBoot_A.cache; import com.study.springboot.SpringBoot_A.SpringBootAApplication; import com.study.springboot.SpringBoot_A.bean.User; import org.junit.Assert;import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.concurrent.TimeUnit; /** * @author 赵超 * @Description * @create 2018-03-23 16:32 **/ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SpringBootAApplication.class) public class TestRedis { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Test public void test() throws Exception { stringRedisTemplate.opsForValue().set("aaa", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); } @Test public void testObj() throws Exception { User user=new User("aa@126.com", "aa", "aa123456", "aa","123"); ValueOperations<String, User> operations=redisTemplate.opsForValue(); operations.set("com.neox", user); operations.set("com.neo.f", user,100, TimeUnit.SECONDS); Thread.sleep(1000); //redisTemplate.delete("com.neo.f"); boolean exists=redisTemplate.hasKey("com.neo.f"); if(exists){ System.out.println("exists is true"); } else { System.out.println("exists is false"); } // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName()); } }
五 自动根据方法生成缓存
@Cacheable(value = "findByUserName") @Override public User findByUserName(String userName) { return userRepository.findByUserName(userName); }
六 共享Session在Redis中
1. 引入依赖 <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> 2. session的配置 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) public class SessionConfig { } maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效 3. 测试 添加测试方法 @RequestMapping("/uid") String uid(HttpSession session) { UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid);return session.getId(); } 4. 多台服务器中共享session 按照上述配置在其他项目中进行相同配置并启动即可