官網:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-redis
集羣文檔:https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#cluster
在SpringBoot2.0中集成redis
第一步:
springboot整合redis相關依賴引入
<!-- redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
第二步:
相關配置文件的引入(yml配置方式),如果密碼沒有,默認就是空,我這裏有密碼就加上了密碼,連接最大時間最好不要設置成-1永不超時,因爲有時候某一個命令數據量特別大,那麼就會卡在那了
redis:
# redis數據庫索引(默認爲0),我們使用索引爲3的數據庫,避免和其他數據庫衝突
database: 0
# redis服務器地址(默認爲localhost)
host: 192.168.17.128
# redis端口(默認爲6379)
port: 6379
# redis訪問密碼(默認爲空)
password: 123456
# redis連接超時時間(單位爲毫秒)
timeout: 3000
#=========redis線程池設置=========
pool:
# 連接池中的最大空閒連接,默認值也是8。
max-active: 8
# 連接池中的最小空閒連接,默認值也是0。
max-idle: 8
#如果賦值爲-1,則表示不限制;pool已經分配了maxActive個jedis實例,則此時pool的狀態爲exhausted(耗盡)。
min-idle: 2000
# 等待可用連接的最大時間,單位毫秒,默認值爲-1,表示永不超時
max-wait: 1000
第三步:
寫controller進行測試,這裏我就舉了最簡單的set,get設置,存取字符串例子:
package net.xdclass.base_project.controller;
import net.xdclass.base_project.domain.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/test/redis")
public class RdisTestController {
@Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate
@GetMapping(value="add")
public Object add(){
//opsForValue : Returns the operations performed on simple values (or Strings in Redis terminology).
redisTpl.opsForValue().set("name", "xdclass2018");
return JsonData.buildSuccess();
}
@GetMapping(value="get")
public Object get(){
String value = redisTpl.opsForValue().get("name");
return JsonData.buildSuccess(value);
}
}
這裏主要注入了StringRedisTemplate這個模板類進行redis的操作,類似於jdbcTemplate,redisTpl能點出許多方法,對不同的redis數據類型進行操作,如下圖所示:
下面啓動項目進行測試:
測試成功!
Redis工具類封裝:
上面代碼中直接操作redis,許多代碼是重複的,比較麻煩,下面我們就封裝一個redis工具類,以簡化開發,這裏只是簡單封裝了幾個方法,其他的方法有需要可以再加,可在開發中使用,注意:在工具類上要加上@Component註解,納入容器管理
package net.xdclass.base_project.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* redis工具類
*/
@Component
public class RedisClient {
@Autowired
private StringRedisTemplate redisTpl; //jdbcTemplate
/**
* 功能描述:設置key-value到redis中
* @param key
* @param value
* @return
*/
public boolean set(String key ,String value){
try{
redisTpl.opsForValue().set(key, value);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
/**
* 功能描述:通過key獲取緩存裏面的值
* @param key
* @return
*/
public String get(String key){
return redisTpl.opsForValue().get(key);
}
/**
* 功能描述:設置某個key過期時間
* @param key
* @param time
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTpl.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 功能描述:根據key 獲取過期時間
* @param key
* @return
*/
public long getExpire(String key){
return redisTpl.getExpire(key,TimeUnit.SECONDS);
}
/**
* 遞增
* @param key 鍵
* @return
*/
public long incr(String key, long delta){
return redisTpl.opsForValue().increment(key, delta);
}
/**
* 遞減
* @param key 鍵
* @param delta 要減少幾
* @return
*/
public long decr(String key, long delta){
return redisTpl.opsForValue().increment(key, -delta);
}
//==============Map結構=====================
//==============List結構=====================
}
這時候我們操作redis只要使用工具類就行了,我們在剛剛的controller中寫兩個接口測試一下工具類:
@GetMapping(value="save_user")
public Object saveUser(){
User user = new User(5,"zhangsan","13122223333",11,new Date());
String userStr = JsonUtils.obj2String(user);
boolean flag = redis.set("base:user:11", userStr);
return JsonData.buildSuccess(flag);
}
@GetMapping(value="find_user")
public Object findUser(){
String userStr = redis.get("base:user:11");
User user = JsonUtils.string2Obj(userStr, User.class);
return JsonData.buildSuccess(user);
}
注意:使用工具類先要將工具類注入進來:
進行測試,成功!
key值命名規範:在開發中key值模塊之間分層使用:隔開,因爲這樣在圖形化工具中展示的會非常清楚,我們以redis Desktop Manager這款圖形工具爲例(具體使用可以自行百度,非常簡單實用):
如圖我們可以非常清楚的看到key值以:爲分隔建立了多個文件夾,這樣就能夠非常直觀的看到我們所存的數據,能夠非常方便的查找
源碼地址:https://gitee.com/xuxinsunqizheng/SpringBoot2.0.git