一伦腐、簡介
Redis是一個開源的使用ANSI C語言編寫赢底、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型柏蘑、Key-Value數(shù)據(jù)庫幸冻,并提供多種語言的API,Redis也是技術(shù)領(lǐng)域使用最為廣泛的存儲中間件咳焚,它是「Remote Dictionary Service」首字母縮寫洽损,也就是「遠程字典服務(wù)」。
Redis相比Memcached提供更多的數(shù)據(jù)類型支持和數(shù)據(jù)持久化操作黔攒。
二趁啸、在Docker中安裝Redis
2.1 下載鏡像
訪問官網(wǎng):https://hub.docker.com/r/library/redis/ 選擇下載版本,本文選擇最新Stable 4.0.11
使用命令拉取鏡像:
docker pull redis:4.0.11
2.2 啟動容器
啟動Redis命令如下:
docker run --name myredis -p 6379:6379 -d redis:4.0.11 redis-server --appendonly yes
命令說明:
- --name 設(shè)置別名
- -p 映射宿主端口到容器端口
- -d 后臺運行
- redis-server --appendonly yes 在容器啟動執(zhí)行redis-server啟動命令督惰,打開redis持久化
啟動成功之后使用命令:
docker ps
查看redis運行請求不傅,如下圖為運行成功:
2.3 使用客戶端連接
連接Redis不錯的GUI工具應(yīng)該是Redis Desktop Manager了,不過現(xiàn)在只有Linux版可以免費下載赏胚,我上傳了一個Windows版本在百度云访娶,版本號為:0.9.5(發(fā)布于2018.08.24)也是比較新的,鏈接: https://pan.baidu.com/s/16npZtnGa3-p2PAafiPEAkA 密碼: 9uqg觉阅,還是免安裝的崖疤,很好用。
Redis Desktop Manager客戶端預覽:
三典勇、Redis集成
開發(fā)環(huán)境
- Spring Boot 2.0.4 RELEASE
- Manven
3.1 添加依賴
在pom.xml添加如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
注意不要依賴“spring-boot-starter-redis”它是舊版本劫哼,新版已經(jīng)遷移到“spring-boot-starter-data-redis”了。
3.2 配置Redis
在application.properties進行如下設(shè)置:
# Redis 配置
# Redis服務(wù)器地址
spring.redis.host=127.0.0.1
# Redis服務(wù)器連接密碼(默認為空)
spring.redis.password=
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis分片(默認為0)Redis默認有16個分片
spring.redis.database=0
# 連接池最大連接數(shù)(使用負值表示沒有限制)
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=10000
# 指定spring的緩存為redis
spring.cache.type=redis
注意:spring.redis.timeout不要設(shè)置為0割笙,設(shè)置為0查詢Redis時會報錯权烧,因為查詢連接時間太短了。
3.3 Redis使用
完成以上配置之后就可以寫代碼操作Redis了伤溉,示例代碼如下:
@Autowired
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("/")
public String doTest() {
String _key = "time"; //緩存key
stringRedisTemplate.opsForValue().set(_key, String.valueOf(new Date().getTime())); //redis存值
return stringRedisTemplate.opsForValue().get(_key); //redis取值
}
更多操作:
- stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS); 向redis里存入數(shù)據(jù)和設(shè)置緩存時間般码;
- stringRedisTemplate.hasKey("keyName"); 檢查key是否存在,返回boolean乱顾;
四板祝、聲明式緩存
為了簡化緩存可以直接使用聲名式緩存,可以省去設(shè)置緩存和讀取緩存的代碼走净,使用起來會方便很多券时。
聲明式緩存使用步驟如下:
4.1 設(shè)置Redis緩存
在pom.xml文件設(shè)置緩存為Redis,代碼如下:
spring.cache.type=redis
4.2 開啟全局緩存
在啟動文件Application.java設(shè)置開啟緩存伏伯,代碼如下:
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.3 使用注解
注解如下:
- @Cacheable 設(shè)置并讀取緩存(第一次設(shè)置以后直接讀雀镂);
- @CachePut 更新緩存(每次刪除并更新緩存結(jié)果)舵鳞;
- @CacheEvict 刪除緩存(只刪除緩存)震檩;
通用屬性:
- value 緩存名稱;
- key 使用SpEL表達式自定義的緩存Key蜓堕,比如:#name是以參數(shù)name為key的緩存抛虏,#resule.name是以返回結(jié)果的name作為key的緩存;
4.3.1 @Cacheable 使用
示例代碼如下:
// 緩存key
private final String _CacheKey = "userCacheKeyTime";
@RequestMapping("/")
@Cacheable(value = _CacheKey)
public String index() {
System.out.println("set cache");
return "cache:" + new Date().getTime();
}
只有首次訪問的時候會在控制臺打印“set cache”信息套才,之后直接返回Redis結(jié)果了迂猴,不會在有添加的打印信息出現(xiàn)。
4.3.2 @CachePut 使用
示例代碼如下:
// 緩存key
private final String _CacheKey = "userCacheKeyTime";
@RequestMapping("/put")
@CachePut(value = _CacheKey)
public String putCache() {
System.out.println("update cache");
return "update cache:" + new Date().getTime();
}
訪問http://xxx/put 每次會把最新的數(shù)據(jù)存儲緩存起來背伴。
4.3.3 @CacheEvict 使用
示例代碼如下:
// 緩存key
private final String _CacheKey = "userCacheKeyTime";
@RequestMapping("/del")
@CacheEvict(value = _CacheKey)
public String delCache() {
System.out.println("緩存刪除");
return "delete cache:" + new Date().getTime();
}
訪問http://xxx/del 只會刪除緩存沸毁,除此之后不會進行任何操作峰髓。
五、分布式Session共享
在分布式系統(tǒng)中Session共享有很多種方案息尺,而把Session托管在緩存中是最常用的方案之一掷邦,下面來看Session在Redis中的托管步驟击罪。
5.1 添加依賴
在pom.xml中添加如下引用:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
5.2 開啟Session功能
在啟動類Application.java的類注解添加開啟Session,代碼如下:
@SpringBootApplication
@EnableCaching
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
其中maxInactiveIntervalInSeconds為Session過期時間,默認30分鐘挟鸠,設(shè)置單位為秒查邢。
5.3 Session使用
接下來編寫一段代碼來測試一下Session票渠,示例代碼如下:
@RequestMapping("/uid")
public String testSession(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return session.getId();
}
連續(xù)訪問兩次請求之后庵朝,查看控制臺信息如下圖:
可以看出,兩次訪問的SessionId是一樣的侮腹,這個時候在查看Redis 客戶端嘲碧,如下圖:
發(fā)現(xiàn)Redis里存儲的Session過期時間也是對的,符合我們的設(shè)置父阻。
5.4 分布式系統(tǒng)共享Session
因為把Session托管給同一臺Redis服務(wù)器了呀潭,所以Session在Spring Boot中按照如上方式在配置多臺服務(wù)器,得到的Session是一樣的至非。
示例源碼下載:https://github.com/vipstone/springboot-example/tree/master/springboot-redis
參考資料
Spring boot中Redis的使用:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html