@author Jacky wang
轉(zhuǎn)載請注明出處 , http://www.reibang.com/p/4cfedabca746
2018年09月12日,第一次補充更新.
看了網(wǎng)上一些Springboot
集成Redis
的很多資料,發(fā)現(xiàn)對Redis
的配置復(fù)雜了,自己總結(jié)了Springboot
集成Redis
的簡單方式冯袍。
一. SpringBoot
集成Redis
單機版
1.1. 創(chuàng)建Maven
工程
搭建SpringBoot工程油宜,包結(jié)構(gòu)如下:
SpringBoot的標(biāo)準(zhǔn)包結(jié)構(gòu)···
1.2. pom
文件添加依賴坯屿,properties
添加配置
pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dream</groupId>
<artifactId>spring-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Springboot集成Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Springboot測試 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 熱部署插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
-----------------------------------------------------------------------------------------------------
application.properties:(很多其實是默認(rèn)的,這里全部列出來)
#指定連接工廠使用的Database index,默認(rèn)為: 0
spring.redis.database=0
#指定Redis server host豁状,默認(rèn)為: localhost
spring.redis.host=127.0.0.1
#指定Redis server的密碼
#spring.redis.password=
#指定連接池最大的活躍連接數(shù)蓝仲,-1表示無限稿械,默認(rèn)為8
spring.redis.pool.max-active=8
#指定連接池最大的空閑連接數(shù)我抠,-1表示無限,默認(rèn)為8
spring.redis.pool.max-idle=8
#指定當(dāng)連接池耗盡時决记,新獲取連接需要等待的最大時間摧冀,以毫秒單位,-1表示無限等待
spring.redis.pool.max-wait=-1
#指定連接池中空閑連接的最小數(shù)量系宫,默認(rèn)為0
spring.redis.pool.min-idle=2
#指定redis服務(wù)端端口索昂,默認(rèn): 6379
spring.redis.port=6379
#指定redis server的名稱
#spring.redis.sentinel.master
#指定sentinel節(jié)點,逗號分隔笙瑟,格式為host:port.
#spring.redis.sentinel.nodes
#指定連接超時時間楼镐,毫秒單位,默認(rèn)為0
spring.redis.timeout=0
1.3. RedisTemplate
的處理
/**
* Redis數(shù)據(jù)庫操作對象
* @author wwj
*/
@Component
public class RedisClient {
@Autowired
private RedisTemplate redisTemplate;
/**
* 寫入緩存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入緩存設(shè)置時效時間
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 讀取緩存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 判斷緩存中是否有對應(yīng)的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 刪除對應(yīng)的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 批量刪除對應(yīng)的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量刪除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
* 哈希獲取數(shù)據(jù)
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}
/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k,v);
}
/**
* 列表獲取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l,l1);
}
/**
* 集合添加
* @param key
* @param value
*/
public void add(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}
/**
* 集合獲取
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}
/**
* 有序集合獲取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key,double scoure,double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
到這里就可以使用,RedisClient
對Redis
進(jìn)行操作了,上面給出的方法比較全,可以選擇需要用到的進(jìn)行使用往枷。
1.4. 測試
1.4.1 Application
入口類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
1.4.2 User實體類
為了測試,還提供了一個User實體類,因為產(chǎn)生了傳輸過程,因此這里必須要實現(xiàn)Serializable接口凄杯。
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private int age;
public User() {
super();
}
public User(String username, int age) {
super();
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [username=" + username + ", age=" + age + "]";
}
}
1.4.3 SpringbootRedisTest
測試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)//指定springboot的啟動類
public class SpringBootRedisTest {
@Autowired
private RedisClient redisClient;
@Test
public void testSet() {
String key = "keyTest";
String val = "keyVal2";
redisClient.set(key, val);
User user = new User("jack", 24);
redisClient.set("user", user);
}
@Test
public void testGet() {
String key = "keyTest";
String key2 = "user";
String val = (String)redisClient.get(key);
User user = (User)redisClient.get(key2);
System.err.println(val);
System.err.println(user);
}
@Test
public void testRemove() {
String key = "keyTest";
String key2 = "user";
redisClient.remove(key);
redisClient.remove(key2);
}
@Test
public void testSetExpire() throws Exception {
String key = "testExpire";
String value = "hello";
long expireTime = 60L;//60秒后消失
redisClient.set(key, value, expireTime);
}
}
以上就是Springboot
集成Redis
的全部過程,實現(xiàn)起來是非常簡單的错洁。到這里總結(jié)一下:
1. 添加pom.xml : spring-boot-starter-data-redis的依賴
2. 配置application.properties
3. 對RedisTemplate進(jìn)行部分功能的封裝。
具體的測試結(jié)果就不貼出來了戒突,這里貼一下testSetExpire()
的結(jié)果屯碴。
二. SpringBoot
集成Redis
集群版
2.1. SpringBoot
集成Redis
集群的兩種方式:
2.1.1. SpringBoot內(nèi)置配置支持:
步驟:
- 引入
Redis
的Maven
依賴 - 配置
application.properties
支持Redis
集群 - 引入
RedisTemplate
使用 - 測試
1. Maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置application.properties支持Redis集群
# RedisProperties
# 在群集中執(zhí)行命令時要遵循的最大重定向數(shù)目。
spring.redis.cluster.max-redirects=3
# (普通集群膊存,不使用則不用開啟)以逗號分隔的“主機:端口”對列表進(jìn)行引導(dǎo)导而。
spring.redis.cluster.nodes=192.168.5.122:9001,192.168.5.122:9002
spring.redis.cluster.timeout=1000\
3. 引入RedisTemplate使用
見單機版的RedisClient
4. 測試
@SpringBootTest(classes = Application.class)
@RunWith(value = SpringRunner.class)
public class TestRedis {
@Autowired
private RedisClient redisClient;
@Test
public void setTest() throws Exception {
List<User> users = new ArrayList<User>();
User user = new User("coco", "coco", "on");
User user2 = new User("jack", "jack", "on");
user.setCreateDate(new Date());
user2.setCreateDate(new Date());
users.add(user);
users.add(user2);
redisClient.set("users", FastJsonUtils.toJSONStringWithDateFormat(users));
}
@Test
public void getTest() throws Exception {
String json = (String) redisClient.get("users");
List<User> users = FastJsonUtils.toList(json, User.class);
for (User record : users) {
System.err.println(record.getUsername());
}
}
}
操作成功。
2.1.2 . 自定義JedisClusterConfig配置類支持Redis集群
步驟:
引入
Redis
的Maven
依賴自定義
Redis
的集群配置并以實體類接收編寫
JedisClusterConfig
的配置類使用
JedisCluster
操作Redis
1. 引入Redis的Maven依賴(省略)
2. 自定義Redis的集群配置并以實體類接收
config/redis.properties:
# 本地環(huán)境集群
jack.redis.pool.nodes=192.168.5.122:9001,192.168.5.122:9002,192.168.5.122:9003
#redis超時時間,單位:秒
jack.redis.pool.timeout=7200
jack.redis.pool.maxAttempts=5
@Component
@ConfigurationProperties(prefix = "jack.redis.pool")
@PropertySource("classpath:/config/redis.properties")
public class RedisProperty {
private String nodes;// redis集群節(jié)點
private int timeout;// 連接超時時間
private int maxAttempts;// 重連次數(shù)
省略getter();setter();
}
3. 編寫 JedisClusterConfig 的配置類
@SpringBootConfiguration
public class JedisClusterConfig {
@Autowired
private RedisProperty redisProperty;
@Bean
public JedisCluster getJedisCluster() {
String[] redisArray = redisProperty.getNodes().split(",");//獲取服務(wù)器數(shù)組,不考慮空指針問題
Set<HostAndPort> nodes = new HashSet<>();
for (String ipport : redisArray) {
String[] ipports = ipport.split(":");
nodes.add(new HostAndPort(ipports[0].trim(), Integer.valueOf(ipports[1].trim())));
}
return new JedisCluster(nodes, redisProperty.getTimeout(), redisProperty.getMaxAttempts());
}
}
4. 使用配置類中的JedisCluster操作Redis
/**
* @ClassName: JedisClusterClient
* @Description:TODO(redis集群的基礎(chǔ)操作工具)
* @author: wwj
* @date: 2018年8月27日 下午3:15:22
*/
@Component
public class JedisClusterClient {
@Autowired
private JedisCluster jedisCluster;
@Autowired
private RedisProperty redisProperty;
/**
* 寫入緩存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
if (value instanceof String) {
jedisCluster.set(key, value.toString());
} else {
jedisCluster.set(key, FastJsonUtils.toJSONStringWithDateFormat(value));
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入緩存設(shè)置時效時間
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
if (value instanceof String) {
jedisCluster.setex(key, Integer.valueOf(expireTime + ""), value.toString());
} else {
jedisCluster.setex(key, Integer.valueOf(expireTime + ""), FastJsonUtils.toJSONStringWithDateFormat(value));
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 設(shè)置緩存隔崎,并且由配置文件指定過期時間
*
* @param key
* @param value
*/
public void setWithExpireTime(String key, String value) {
try {
int expireSeconds = redisProperty.getTimeout();
set(key, value, Long.valueOf(expireSeconds));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取緩存
*
* @param key
* @return
*/
public String get(final String key) {
return jedisCluster.get(key);
}
/**
* 判斷緩存中是否有對應(yīng)的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return jedisCluster.exists(key);
}
/**
* 刪除對應(yīng)的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
jedisCluster.del(key);
}
}
/**
* 批量刪除對應(yīng)的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
}