REmote DIctionary Server(Redis) 是一個由Salvatore Sanfilippo寫的key-value存儲系統。
Redis是一個開源的使用ANSI C語言編寫、遵守BSD協議、支持網絡、可基於內存亦可持久化的日志型、Key-Value數據庫,並提供多種語言的API。
它通常被稱為數據結構服務器,因為值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等類型。
Redis是目前行業使用最廣泛的內存數據存儲。比memcached更受歡迎,Redis支持更豐富的數據結構,同時支持數據持久化。
除此之外,Redis還提供一些類數據庫的特性,比如事務,HA,主從庫。可以說Redis兼具了緩存系統和數據庫的一些特性,因此有着豐富的應用場景。
redis在SpringBoot2.0版本后如何使用
第一步:引入spring-boot-starter-data-redis依賴包
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-redis</artifactId> 4 </dependency>
第二步:編寫配置文件application.yml(當然,也可以通過profile機制指向不同的環境配置文件)
spring:
# profiles:
# active: dev
redis:
database: 0
host: www.weiyi.com
password: null
max-active: 8
max-idle: 500
max-wait: 1
min-idle: 0
port: 6379
timeout: 5000ms
第三步:添加redis的Java配置類
1 package ooh.chaos.configuration; 2 3 import ooh.chaos.configuration.FastJsonRedisSerializer; 4 import org.springframework.cache.annotation.CachingConfigurerSupport; 5 import org.springframework.cache.annotation.EnableCaching; 6 import org.springframework.context.annotation.Bean; 7 import org.springframework.context.annotation.Configuration; 8 import org.springframework.data.redis.connection.RedisConnectionFactory; 9 import org.springframework.data.redis.core.RedisTemplate; 10 import org.springframework.data.redis.serializer.StringRedisSerializer; 11 12 import org.springframework.cache.interceptor.KeyGenerator; 13 import org.springframework.session.SessionRepository; 14 import org.springframework.session.data.redis.RedisOperationsSessionRepository; 15 16 /** 17 * redis 配置 18 */ 19 @Configuration 20 @EnableCaching 21 public class RedisConfig extends CachingConfigurerSupport { 22 23 @Bean 24 @Override 25 public KeyGenerator keyGenerator() { 26 return (target, method, params) -> { 27 StringBuilder sb = new StringBuilder(); 28 sb.append(target.getClass().getName()); 29 sb.append(method.getName()); 30 for (Object obj : params) { 31 sb.append(obj.toString()); 32 } 33 return sb.toString(); 34 }; 35 } 36 37 /** 38 * 設置 redisTemplate 序列化方式 39 * 40 * @param factory 41 * @return 42 */ 43 @Bean 44 public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) { 45 RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>(); 46 redisTemplate.setConnectionFactory(factory); 47 // 設置值(value)的序列化采用FastJsonRedisSerializer。 48 FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); 49 redisTemplate.setValueSerializer(fastJsonRedisSerializer); 50 redisTemplate.setHashValueSerializer(fastJsonRedisSerializer); 51 // 設置鍵(key)的序列化采用StringRedisSerializer。 52 redisTemplate.setKeySerializer(new StringRedisSerializer()); 53 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); 54 redisTemplate.setDefaultSerializer(fastJsonRedisSerializer); 55 redisTemplate.afterPropertiesSet(); 56 return redisTemplate; 57 } 58 59 /** 60 * 設置spring session redis 序列化方式 61 * 62 * @param factory 63 * @return 64 */ 65 @Bean 66 public SessionRepository sessionRepository(RedisConnectionFactory factory) { 67 RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository( 68 redisTemplate(factory)); 69 FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); 70 sessionRepository.setDefaultSerializer(fastJsonRedisSerializer); 71 sessionRepository.setDefaultMaxInactiveInterval(36000); 72 return sessionRepository; 73 } 74 75 }
最后一步:在SpringBoot項目中使用redis
1.引入redis操作bean
1 @Autowired 2 private RedisTemplate<Object, Object> redisTemplate;
2.使用redisTemplate操作redis,手動使用方式
1 // 增加token邏輯,Created by xiaoshiyilang on 2018/10/19 2 String md5Key = DigestUtils.md5Hex(Constants.TOKEN_KEY_PRE + user.getUid()); 3 if (redisTemplate.opsForValue().get(md5Key) != null) { 4 redisTemplate.delete(md5Key); 5 } 6 String md5Token = DigestUtils.md5Hex(generalToken() + user.getUid()); 7 if (redisTemplate.opsForValue().get(md5Token) != null) { 8 redisTemplate.delete(md5Token); 9 } 10 // 返回給前端的Token 11 redisTemplate.opsForValue().set(md5Key, md5Token); 12 // 設置Token過期時間 13 redisTemplate.expire(md5Key, 86400 * 30, TimeUnit.SECONDS); 14 // 記錄成功的用戶id 15 redisTemplate.opsForValue().set(md5Token, user.getUid()); 16 // 設置登錄用戶過期時間 17 redisTemplate.expire(md5Token, 86400 * 30, TimeUnit.SECONDS);
另一種使用方式:自動根據方法生成緩存
1 @Cacheable(value = "user-key") 2 public User getUser(Long id) { 3 User user = userService.selectByPrimaryKey(id); 4 System.out.println("若下面沒出現“無緩存的時候調用”字樣且能打印出數據表示測試成功"); 5 return user; 6 }
其中value的值就是緩存到redis中的key。
SpringBoot下使用Redis實現session共享
分布式系統中,session會面臨需要在多個項目中共享的問題,包括集群,負載均衡也是需要session共享的,有很多的解決方案,其中托管到redis這樣的緩存中是最常用的方案之一,小Alan在這里也和大家聊一聊
第一步:引入spring-session-data-redis依賴包
1 <dependency> 2 <groupId>org.springframework.session</groupId> 3 <artifactId>spring-session-data-redis</artifactId> 4 </dependency>
第二步:添加session的Java配置類
1 package com.only.tech.user.configuration; 2 3 import org.springframework.context.annotation.Configuration; 4 import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; 5 6 /** 7 * session配置,30分鍾過期 8 */ 9 @Configuration 10 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 30) 11 public class SessionConfig { 12 13 }
maxInactiveIntervalInSeconds: 設置Session失效時間,使用Redis Session之后,原Boot的server.session.timeout屬性不再生效。
最后一步:測試session是否生效
添加測試方法獲取sessionid
1 @RequestMapping("/uid") 2 String uid(HttpSession session) { 3 UUID uid = (UUID) session.getAttribute("uid"); 4 if (uid == null) { 5 uid = UUID.randomUUID(); 6 } 7 session.setAttribute("uid", uid); 8 return session.getId(); 9 }
登錄redis客戶端查看是否保存sessionid相關的值

訪問瀏覽器執行多個請求如果是同一個sessionid就說明session已經在redis中進行有效的管理了。
如何在兩個項目或者多個項目中共享session(或者多台機器)
按照上面的步驟在另一個項目中再次配置一次session,啟動項目后自動就進行了session的共享機制。
注意:我在redis的Java配置類中設置了spring session redis 的序列化方式,因為我這里沒有使用SpringBoot默認的json序列化方式,而是使用了阿里的fastjson。
結束語:這城市總是風很大,孤獨的人晚回家,外面不像你想的那么好,風雨都要直接擋。願每個獨自走夜路的你,都足夠堅強。
佛系博主:AlanLee
博客地址:http://www.cnblogs.com/AlanLee
GitHub地址:https://github.com/AlanLee-Java
本文出自博客園,歡迎大家加入博客園。
