一、Maven依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 引入 Redis 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 引入單元測試依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 接下來三個是jackson的依賴 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
二、application.yml配置
spring:
### 配置Redis
# Redis數據庫索引(默認爲0)
redis:
database: 0
# Redis服務器地址
host: 172.16.250.238
# Redis服務器連接端口
port: 6379
# Redis服務器連接密碼(默認爲空)
password: 123456
# 配置連接池
jedis:
pool:
# 連接池最大連接數(使用負值表示沒有限制)
max-active: 8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-wait: -1
# 連接池中的最大空閒連接
max-idle: 500
# 連接池中的最小空閒連接
min-idle: 0
# 連接超時時間(毫秒)
timeout: 2000
lettuce:
shutdown-timeout: 0
三、StringRedisTemplate與RedisTemplate測試
完成上述兩個步驟之後,Springboot就會在應用啓動時自動地爲我們裝配好StringRedisTemplate和RedisTemplate的Bean。下面寫一個JUNIT來測試一下:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRedisApplicationTests {
@Autowired
private ApplicationContext context;
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void RedisTemplateTest() {
System.out.println(redisTemplate); // 結果: org.springframework.data.redis.core.RedisTemplate@314c8b4a
redisTemplate.opsForValue().set("db-type", "redis");
System.out.println(redisTemplate.opsForValue().get("db-type")); // 結果: redis
}
@Test
public void StringRedisTemplateTest() {
System.out.println(stringRedisTemplate); // 結果: org.springframework.data.redis.core.RedisTemplate@314c8b4a
stringRedisTemplate.opsForValue().set("db-type", "mongodb");
System.out.println(stringRedisTemplate.opsForValue().get("db-type")); // 結果: mongodb
System.out.println(redisTemplate.opsForValue().get("db-type")); // 結果: redis
}
@Test
public void RedisConnectionFactoryTest() {
RedisConnectionFactory redisConnectionFactoryBean = context.getBean(RedisConnectionFactory.class);
System.out.println(redisConnectionFactoryBean); // 結果: org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory@59496961
}
}
需要知道的是:
1. StringRedisTemplate繼承自RedisTemplate;
2. 從測試結果可以看出 StringRedisTemplate和RedisTemplate所管理的數據是相互獨立的,對其中一個的數據進行修改並不會對另一個的數據產生影響。
3. SDR默認採用的序列化策略有兩種,一種是String的序列化策略,一種是JDK的序列化策略。
-
StringRedisTemplate默認採用的是String的序列化策略,保存的key和value都是採用此策略序列化保存的。
-
RedisTemplate默認採用的是JDK的序列化策略,保存的key和value都是採用此策略序列化保存的。
四、自己創建RedisTemplate Bean
public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {}
注意:如果沒特殊情況,切勿定義成RedisTemplate<Object, Object>,否則根據里氏替換原則,使用的時候會造成類型錯誤 。推薦定義成 RedisTemplate<String, Object>。
常見問題:在使用@Autowired註解裝配RedisTemplate<String, Object>時由於泛型不匹配會出現如下錯誤:
Could not autowire. No beans of 'RedisTemplate<String, Object>' type found.
解決辦法:改用 @Resource 註解(@Autowired根據類型裝配Bean,@Resource根據名稱進行裝配)。
或者,自己定義一個RedisTemplate<String, Object> Bean,而不再讓Spring爲我們創建RedisTemplate<Object, Object> Bean。這樣即使使用@Autowired註解也可以成功裝配RedisTemplate<String, Object> Bean。
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author pengjunlee
* @create 2019-09-10 9:59
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(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);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key採用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也採用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式採用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式採用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
五、Redis工具類
將RedisTemplate的常用API封裝成一個工具類RedisUtil.java。
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author pengjunlee
* @create 2019-09-10 10:02
*/
@Component
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 指定緩存失效時間
*
* @param key
* @param time 時間(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據key 獲取過期時間
*
* @param key
* @return 時間(秒) 返回0代表爲永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* @param key
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除鍵值
*
* @param key 可以傳一個值 或多個
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* 獲取鍵值
*
* @param key
* @return
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 設置鍵值
*
* @param key
* @param value
* @return true成功 false失敗
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 設置鍵值同時指定過期時間
*
* @param key
* @param value
* @param time 時間(秒) time要大於0 如果time小於等於0 將設置無限期
* @return true成功 false 失敗
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 鍵值遞增
*
* @param key
* @param delta 要增加幾(大於0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("遞增因子必須大於0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 鍵值遞減
*
* @param key
* @param delta 要減少幾(小於0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("遞減因子必須大於0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
/**
* 獲取HashGet
*
* @param key
* @param item
* @return
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 設置HashGet
*
* @param key
* @return
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 設置多個HashGet
*
* @param key
* @param map
* @return
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 設置多個HashGet時指定過期時間
*
* @param key
* @param map
* @param time 時間(秒)
* @return
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一張hash表中放入數據,如果不存在將創建
*
* @param key
* @param item
* @param value
* @return true 成功 false失敗
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一張hash表中放入數據,如果不存在將創建
*
* @param key
* @param item
* @param value
* @param time 時間(秒) 注意:如果已存在的hash表有時間,這裏將會替換原有的時間
* @return true 成功 false失敗
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除hash表中的值
*
* @param key
* @param item
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判斷hash表中是否存在item
*
* @param key
* @param item
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash遞增 如果不存在,就會創建一個 並把新增後的值返回
*
* @param key
* @param item
* @param by 要增加的值(大於0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash遞減
*
* @param key
* @param item
* @param by 要減少的值(小於0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
/**
* 獲取set的內容
*
* @param key
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 判斷set中是否存在某個值
*
* @param key
* @param value
* @return
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 設置set
*
* @param key
* @param values
* @return
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 設置set同時指定過期時間
*
* @param key
* @param time 時間(秒)
* @param values
* @return
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 獲取set的元素個數
*
* @param key
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 從set中移除元素
*
* @param key
* @param values
* @return
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 獲取List的內容
*
* @param key
* @param start 開始索引
* @param end 結束索引 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 獲取list的長度
*
* @param key
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通過索引 獲取list中的值
*
* @param key
* @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 設置List
*
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 設置List
*
* @param key
* @param value
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 設置List
*
* @param key
* @param value
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 設置List同時指定過期時間
*
* @param key
* @param value
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據索引修改list中的某條數據
*
* @param key
* @param index
* @param value
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N個值爲value
*
* @param key
* @param count
* @param value
* @return 移除的個數
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
在需要操作Redis的類中通過@Autowired註解引人RedisUtil Bean進行使用。
@Autowired
private RedisUtil redisUtil;
@Test
public void MapTest() {
Map<String, String> map = new HashMap<>(16);
map.put("db-type", "redis");
redisUtil.set("data", map); // 結果: ["java.util.HashMap",{"db-type":"redis"}]
Map<String, String> data = (Map<String, String>) redisUtil.get("data");
System.out.println(data.get("db-type")); // 結果: redis
}
@Test
public void ListTest() {
List<User> list = new ArrayList<>(16);
list.add(new User("tracy", 18));
list.add(new User("graython", 24));
redisUtil.set("data", list); // 結果: ["java.util.ArrayList",[["com.pengjunlee.springredis.domain.User",{"name":"tracy","age":18}],["com.pengjunlee.springredis.domain.User",{"name":"graython","age":24}]]]
List<User> users = (List<User>) redisUtil.get("data");
System.out.println(users.get(1).getName()); // 結果: graython
}