文章目錄
1.引入依賴
有以下兩種方式:
方式1:
在新建項目時勾選以下依賴即可
方式2:
手動將以下依賴添加進pom.xml文件中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置Redis
配置Redis需要針對兩方面進行配置。
一是連接屬性
- Redis服務器地址
- Redis服務器端口號
- 連接密碼
- 數據庫索引
- 超時時間
二是配置Redis連接池屬性
- 連接池大小
- 等待時間
- 空閒時間
SpringBoot默認使用的是lettuce連接池,這一點通過依賴關係就可以看到:
除此之外,還需要添加commons-pool2依賴,否則無法使用lettuce連接池
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
配置代碼如下:
spring:
redis:
#設置服務器地址,默認爲localhost
host: 127.0.0.1
#設置服務器端口號,默認爲6379
port: 6379
#Redis默認不需要連接密碼
password:
#設置數據庫索引,默認爲0
database: 0
#設置連接超時時間
timeout: 5000ms
lettuce:
pool:
#連接池大小,默認爲8
max-active: 20
#最大空閒連接數
max-idle: 20
#最小空閒連接數,只有在time-between-eviction-runs設置爲正值時纔有效
min-idle: 0
#獲取連接的最大阻塞等待時間(-1表示不限制)
max-wait: 30s
#空閒連接檢查線程運行週期
time-between-eviction-runs: 3000ms
3.操作Redis
Redis有五大數據類型:
- String:<key,value>
- Hash:<key,fields-values>
- List:有順序可重複
- Set:無順序不可重複
- Zset(Sorted Sets):有順序,不可重複
操作Redis即操作這五大數據類型,SpringBoot爲我們提供了StringRedisTemplate和RedisTemplate用來操作Redis。StringRedisTemplate專門用來操作字符串,RedisTemplate可以用來操作複雜數據類型。接下來看一看他們怎麼用吧。
3.1 操作字符串
示例代碼如下
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
void StringRedisTemplateTest() {
//設置或更新 key value
stringRedisTemplate.opsForValue().set("name", "hello");
//追加值
stringRedisTemplate.opsForValue().append("name", "World");
String nameValue = stringRedisTemplate.opsForValue().get("name");
System.out.println(nameValue);
stringRedisTemplate.opsForList().leftPush("list1", "aaa");
stringRedisTemplate.opsForList().leftPush("list1", "bbb");
stringRedisTemplate.opsForList().leftPush("list1", "ccc");
List<String> list1 = stringRedisTemplate.opsForList().range("list1", 0, -1);
System.out.println(list1);
}
運行效果:
StringRedisTemplate類操作五大數據類型的API:
stringRedisTemplate.opsForValue();
stringRedisTemplate.opsForList();
stringRedisTemplate.opsForSet();
stringRedisTemplate.opsForZSet();
stringRedisTemplate.opsForHash();
3.2 操作複雜數據類型
準備工作,創建Employee類:
public class Employee {
private Integer id;
private String name;
private Double salary;
private Date birthday;
public Employee(Integer id, String name, Double salary, Date birthday) {
this.id = id;
this.name = name;
this.salary = salary;
this.birthday = birthday;
}
public Employee() {
}
getter/setter方法
toString方法
}
使用RedisTemplate操作複雜數據類型:
@Autowired
RedisTemplate redisTemplate;
@Test
void redisTemplateTest() {
Employee employee1 = new Employee(1, "george", 13000D, new Date());
Employee employee2 = new Employee(2, "peter", 13000D, new Date());
Employee employee3 = new Employee(3, "mark", 13000D, new Date());
redisTemplate.opsForValue().set("employee::1", employee1);
Employee e = (Employee) redisTemplate.opsForValue().get("employee::1");
System.out.println(e);
redisTemplate.opsForList().leftPush("employees", employee1);
redisTemplate.opsForList().leftPush("employees", employee2);
redisTemplate.opsForList().leftPush("employees", employee3);
List<Employee> employees = redisTemplate.opsForList().range("employees", 0, -1);
System.out.println(employees);
}
在執行過程中,你會發現出現了以下錯誤:
這是因爲如果想要將象存儲到Redis,需要將對象進行序列化,這樣才能將對象轉換成字節流,以及將字節流轉換成對象讀取出來。
序列化方法很簡單,Employee 類實現Serializable接口就可以了:
public class Employee implements Serializable {
private Integer id;
private String name;
private Double salary;
private Date birthday;
......
}
運行效果
數據庫中存儲employee::1對象的序列化信息
數據庫中存儲employees的序列化信息
可以發現,在使用默認的RedisTemplate存儲複雜類型數據時,無論是key還是value都是採用JDK提供的序列化方式進行存儲的。這就導致了我們查看數據庫時一點也不方便,這時就需要我們自定義RedisTemplate了。
4.自定義Redis
我們需要自定義一個RedisTemplate,並將其默認的序列化器指定爲JSON序列化器,這樣我們就能看懂數據庫裏的數據了。
4.1 自定義RedisTemplate
要想使用JSON序列化器需要引入依賴spring-boot-starter-json
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
編寫配置類config.RedisConfig
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> jsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
template.setDefaultSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4.2 使用自定義RedisTemplate
@Autowired
RedisTemplate jsonRedisTemplate;
@Test
void jsonRedisTemplateTest() {
Employee employee1 = new Employee(1, "george", 13000D, new Date());
Employee employee2 = new Employee(2, "peter", 13000D, new Date());
Employee employee3 = new Employee(3, "mark", 13000D, new Date());
jsonRedisTemplate.opsForValue().set("employee::" + employee1.getId(), employee1);
jsonRedisTemplate.opsForValue().set("employee::" + employee2.getId(), employee2);
Employee e = (Employee) jsonRedisTemplate.opsForValue().get("employee::1");
System.out.println(e);
jsonRedisTemplate.opsForList().leftPush("employees", employee1);
jsonRedisTemplate.opsForList().leftPush("employees", employee2);
jsonRedisTemplate.opsForList().leftPush("employees", employee3);
List<Employee> employees = jsonRedisTemplate.opsForList().range("employees", 0, -1);
System.out.println(employees);
}
運行效果:
數據庫中存儲的數據:
這樣就清晰明瞭了。
5.自定義Redis工具類
每次操作數據前面都跟上一大串:jsonRedisTemplate.opsForValue().xxxx,jsonRedisTemplate.opsForList().xxxx…實在麻煩。
下面貼上一個自定義Redis工具類,參考自https://blog.csdn.net/qq_19734597/article/details/92798699(在此感謝作者的無私分享)
package com.springboot.utils;
/**
* @Auther: yky
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis工具類
*/
@Component
public class RedisClient {
@Autowired
private RedisTemplate jsonRedisTemplate;
/**
* 指定緩存失效時間
* @param key 鍵
* @param time 時間(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
jsonRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據key 獲取過期時間
* @param key 鍵 不能爲null
* @return 時間(秒) 返回0代表爲永久有效
*/
public long getExpire(String key) {
return jsonRedisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判斷key是否存在
* @param key 鍵
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return jsonRedisTemplate.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) {
jsonRedisTemplate.delete(key[0]);
} else {
jsonRedisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
public void del(Integer key) {
this.del(String.valueOf(key));
}
// ============================String=============================
/**
* 普通緩存獲取
* @param key 鍵
* @return 值
*/
public Object get(String key) {
return key == null ? null : jsonRedisTemplate.opsForValue().get(key);
}
public Object get(Integer key) {
return this.get(String.valueOf(key));
}
/**
* 普通緩存放入
* @param key 鍵
* @param value 值
* @return true成功 false失敗
*/
public boolean set(String key, Object value) {
try {
jsonRedisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(Integer key, Object value) {
return this.set( String.valueOf(key) , value);
}
/**
* 普通緩存放入並設置時間
* @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) {
jsonRedisTemplate.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 jsonRedisTemplate.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 jsonRedisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
* @param key 鍵 不能爲null
* @param item 項 不能爲null
* @return 值
*/
public Object hget(String key, String item) {
return jsonRedisTemplate.opsForHash().get(key, item);
}
/**
* 獲取hashKey對應的所有鍵值
* @param key 鍵
* @return 對應的多個鍵值
*/
public Map<Object, Object> hmget(String key) {
return jsonRedisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 鍵
* @param map 對應多個鍵值
* @return true 成功 false 失敗
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
jsonRedisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 並設置時間
* @param key 鍵
* @param map 對應多個鍵值
* @param time 時間(秒)
* @return true成功 false失敗
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
jsonRedisTemplate.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 {
jsonRedisTemplate.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 {
jsonRedisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除hash表中的值
* @param key 鍵 不能爲null
* @param item 項 可以使多個 不能爲null
*/
public void hdel(String key, Object... item) {
jsonRedisTemplate.opsForHash().delete(key, item);
}
/**
* 判斷hash表中是否有該項的值
* @param key 鍵 不能爲null
* @param item 項 不能爲null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return jsonRedisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash遞增 如果不存在,就會創建一個 並把新增後的值返回
* @param key 鍵
* @param item 項
* @param by 要增加幾(大於0)
* @return
*/
public double hincr(String key, String item, double by) {
return jsonRedisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash遞減
* @param key 鍵
* @param item 項
* @param by 要減少記(小於0)
* @return
*/
public double hdecr(String key, String item, double by) {
return jsonRedisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根據key獲取Set中的所有值
* @param key 鍵
* @return
*/
public Set<Object> sGet(String key) {
try {
return jsonRedisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根據value從一個set中查詢,是否存在
* @param key 鍵
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return jsonRedisTemplate.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 jsonRedisTemplate.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 = jsonRedisTemplate.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 jsonRedisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值爲value的
* @param key 鍵
* @param values 值 可以是多個
* @return 移除的個數
*/
public long setRemove(String key, Object... values) {
try {
Long count = jsonRedisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 獲取list緩存的內容
* @param key 鍵
* @param start 開始
* @param end 結束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return jsonRedisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 獲取list緩存的長度
* @param key 鍵
* @return
*/
public long lGetListSize(String key) {
try {
return jsonRedisTemplate.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 jsonRedisTemplate.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 {
jsonRedisTemplate.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 {
jsonRedisTemplate.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 {
jsonRedisTemplate.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 {
jsonRedisTemplate.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 {
jsonRedisTemplate.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 = jsonRedisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
簡單使用它
@Autowired
RedisClient redisClient;
@Test
void redisClientTest()
{
redisClient.set("employee::3", new Employee(3, "mark", 13000D, new Date()));
redisClient.set("key1", "value1");
Employee e = (Employee) redisClient.get("employee::3");
String value = (String) redisClient.get("key1");
System.out.println(e);
System.out.println(value);
redisClient.hset("myHash","employee::1", new Employee(1, "george", 13000D, new Date()));
redisClient.hset("myHash","employee::2", new Employee(2, "peter", 13000D, new Date()));
redisClient.hset("myHash","employee::3", new Employee(3, "mark", 13000D, new Date()));
e = (Employee) redisClient.hget("myHash", "employee::1");
System.out.println(e);
Map<Object,Object> maps = redisClient.hmget("myHash");
System.out.println(maps);
}
控制檯輸出: