spring boot對經常使用的數據庫支持外,對nosql 數據庫也進行了封裝自動化。redis
Redis是目前業界使用最普遍的內存數據存儲。相比memcached,Redis支持更豐富的數據結構,例如hashes, lists, sets等,同時支持數據持久化。除此以外,Redis還提供一些類數據庫的特性,好比事務,HA,主從庫。能夠說Redis兼具了緩存系統和數據庫的一些特性,所以有着豐富的應用場景。本文介紹Redis在Spring Boot中兩個典型的應用場景。spring
1.引入 spring-boot-starter-redissql
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
2.添加配置文件數據庫
# REDIS (RedisProperties) # Redis數據庫索引(默認爲0) spring.redis.database=0 # Redis服務器地址 spring.redis.host=192.168.1.111 # 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
3.添加cache的配置類緩存
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ @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(); } }; } @SuppressWarnings("rawtypes") @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; } }
4.接下來就能夠直接使用了服務器
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class TestRedis { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Test public void test() throws Exception { stringRedisTemplate.opsForValue().set("A", "1"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("A")); } @Test public void testObj() throws Exception { User user=new User("test@qq.com", "test", "123456", "test","123456"); ValueOperations<String, User> operations=redisTemplate.opsForValue(); operations.set("com.neox", user); operations.set("com.neo.f", user,1,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()); } }
以上都是手動使用的方式,如何在查找數據庫的時候自動使用緩存呢,看下面;session
5.自動根據方法生成緩存數據結構
@RequestMapping("/getUser") @Cacheable(value="user-key") public User getUser() { User user=userRepository.findByUserName("aa"); System.out.println("若下面沒出現「無緩存的時候調用」字樣且能打印出數據表示測試成功"); return user; }
其中value的值就是緩存到redis中的keyapp
分佈式系統中,sessiong共享有不少的解決方案,其中託管到緩存中應該是最經常使用的方案之一,dom
Spring Session provides an API and implementations for managing a user’s session information.
1.引入依賴
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
2.Session配置:
@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) public class SessionConfig { }
maxInactiveIntervalInSeconds: 設置Session失效時間,使用Redis Session以後,原Boot的server.session.timeout屬性再也不生效
3.測試
添加測試方法獲取sessionid
@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(); }
登陸redis 輸入 keys '*sessions*'
t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4 t(spring:session:expirations:1472976480000
其中 1472976480000爲失效時間,意思是這個時間後session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4
爲sessionId,登陸http://localhost:8080/uid 發現會一致,就說明session 已經在redis裏面進行有效的管理了。
按照上面的步驟在另外一個項目中再次配置一次,啓動後自動就進行了session共享。