遠(yuǎn)程連接Jedis和整合SpringBoot的詳細(xì)過(guò)程
一、遠(yuǎn)程連接Jedis
1、導(dǎo)入Jedis所需的jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
2、遠(yuǎn)程連接Redis注意事項(xiàng)
- 禁用Linux的防火墻:systemctl stop/disable firewalld.service
- 在配置文件redis.conf中注釋掉bind 127.0.0.1 ,然后修改protected-mode no
3、Jedis測(cè)試遠(yuǎn)程連接
package com.hcz;
import redis.clients.jedis.Jedis;
public class TestPing {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
jedis.close();
}
}

4、常用的數(shù)據(jù)類型
(1)Key
package com.hcz;
import redis.clients.jedis.Jedis;
import java.util.Set;
public class TestKey {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
System.out.println("判斷某個(gè)鍵知否存在:"+jedis.exists("username"));
System.out.println("新增<'username','hcz'>的鍵值對(duì)"+jedis.set("username","hcz"));
System.out.println("新增<'password','123'>的鍵值對(duì)"+jedis.set("password","123"));
System.out.println("系統(tǒng)中所有的鍵如下:");
Set<String> keys = jedis.keys("*");
System.out.println(keys);
System.out.println("獲取username的值:"+jedis.get("username"));
System.out.println("獲取password的值:"+jedis.get("password"));
System.out.println("刪除鍵password"+jedis.del("password"));
System.out.println("判斷password是否存在:"+jedis.exists("password"));
System.out.println("查看鍵username所存儲(chǔ)的值的類型:"+jedis.type("username"));
System.out.println("隨機(jī)返回key空間的一個(gè):"+jedis.randomKey());
System.out.println("重命名key:"+jedis.rename("username","newname"));
System.out.println("取出重命名后的newname:"+jedis.get("newname"));
System.out.println("按索引查詢:"+jedis.select(0));
System.out.println("清空當(dāng)前數(shù)據(jù)庫(kù)所有的key:"+jedis.flushDB());
System.out.println("返回當(dāng)前數(shù)據(jù)庫(kù)中key的數(shù)目:"+jedis.dbSize());
System.out.println("刪除所有數(shù)據(jù)庫(kù)中的key:"+jedis.flushAll());
jedis.close();
}
}

(2)String
package com.hcz;
import redis.clients.jedis.Jedis;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class TestString {
public static void main(String[] args) {
Jedis jedis = new Jedis("139.196.236.217",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
System.out.println("====增加數(shù)據(jù)====");
System.out.println(jedis.set("k1","v1"));
System.out.println(jedis.set("k2","v2"));
System.out.println(jedis.set("k3","v3"));
System.out.println("刪除鍵k2:"+jedis.del("k2"));
System.out.println("獲取鍵k2:"+jedis.get("k2"));
System.out.println("獲取鍵k1:"+jedis.get("k1"));
System.out.println("修改鍵k3:"+jedis.set("k3","new_v3"));
System.out.println("獲取k3的值:"+jedis.get("k3"));
System.out.println("在k3后面加值:"+jedis.append("k3","End"));
System.out.println("獲取k3的值:"+jedis.get("k3"));
System.out.println("增加多個(gè)鍵值對(duì):"+jedis.mset("k4","v4","k5","v5"));
System.out.println("獲取多個(gè)鍵值對(duì):"+jedis.mget("k3","k4","k5"));
System.out.println("刪除多個(gè)鍵值對(duì):"+jedis.del("k1","k3"));
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
System.out.println("====新增鍵值對(duì)防止覆蓋原先值====");
System.out.println(jedis.setnx("k1","v1"));
System.out.println(jedis.setnx("k2","v2"));
System.out.println(jedis.setnx("k2","v2-new"));
System.out.println("獲取k1的值"+jedis.get("k1"));
System.out.println("獲取k2的值"+jedis.get("k2"));
System.out.println("====新增鍵值并設(shè)置有效時(shí)間====");
System.out.println(jedis.setex("k3",2,"v3"));
System.out.println("第一次獲取k3的值"+jedis.get("k3"));
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二次獲取k3的值"+jedis.get("k3"));
System.out.println("====獲取原值,更新為新值=====");
System.out.println(jedis.getSet("k2","k2-getset"));
System.out.println(jedis.get("k2"));
System.out.println("獲得k2的值的字串:"+jedis.getrange("k2",2,4));
jedis.close();
}
}


(3)List
package com.hcz;
import redis.clients.jedis.Jedis;
public class TestList {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
System.out.println("====增加一個(gè)list====");
jedis.lpush("collections","ArrayList","Vector","Stack","HashMap","WeakHashMap","LinkedHashMap");
jedis.lpush("collections","HashSet");
jedis.lpush("collections","TreeSet");
jedis.lpush("collections","TreeMap");
System.out.println("collections的內(nèi)容:"+jedis.lrange("collections",0,-1));
System.out.println("collections區(qū)間的0-3號(hào)元素:"+jedis.lrange("collections",0,3));
System.out.println("===========================");
//刪除指定的值,第二個(gè)參數(shù)為刪除的個(gè)數(shù)(有重復(fù)時(shí)),后add進(jìn)去的值先被刪除,類似出棧
System.out.println("刪除指定元素個(gè)數(shù)"+jedis.lrem("collections",2,"HashMap"));
System.out.println("collections的內(nèi)容:"+jedis.lrange("collections",0,-1));
System.out.println("collections列表出棧(左端):"+jedis.lpop("collections"));
System.out.println("collections的內(nèi)容:"+jedis.lrange("collections",0,-1));
System.out.println("collections添加元素,從列表右端,與lpush相對(duì)應(yīng):"+jedis.rpush("collections","List","Set","String"));
System.out.println("collections的內(nèi)容:"+jedis.lrange("collections",0,-1));
System.out.println("collections列表出棧(右端):"+jedis.rpop("collections"));
System.out.println("collections的內(nèi)容:"+jedis.lrange("collections",0,-1));
System.out.println("修改collections指定下標(biāo)為1的內(nèi)容:"+jedis.lset("collections",1,"newHashSet"));
System.out.println("collections的內(nèi)容:"+jedis.lrange("collections",0,-1));
System.out.println("===============================");
System.out.println("collections的長(zhǎng)度:"+jedis.llen("collections"));
System.out.println("獲取collections下標(biāo)為2的元素:"+jedis.lindex("collections",2));
System.out.println("===============================");
jedis.lpush("sortList","3","5","2","8","6","0");
System.out.println("sortList排序前:"+jedis.lrange("sortList",0,-1));
System.out.println(jedis.sort("sortList"));
System.out.println("sortList排序后:"+jedis.lrange("sortList",0,-1));
jedis.close();
}
}

(4)Set
package com.hcz;
import redis.clients.jedis.Jedis;
import java.util.Set;
public class TestSet {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
System.out.println("==========向集合中添加元素(不重復(fù))");
System.out.println(jedis.sadd("eleSet","e1","e0","e3","e6","e5","e7","e8"));
System.out.println(jedis.sadd("eleSet","e4"));
System.out.println(jedis.sadd("eleSet","e4"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("刪除一個(gè)元素e0:"+jedis.srem("eleSet","e0"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("刪除二個(gè)元素e7,e6:"+jedis.srem("eleSet","e7","e6"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("隨機(jī)的移除集合中的一個(gè)元素:"+jedis.spop("eleSet"));
System.out.println("隨機(jī)的移除集合中的一個(gè)元素:"+jedis.spop("eleSet"));
System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
System.out.println("eleSet的元素個(gè)數(shù)為:"+jedis.scard("eleSet"));
System.out.println("e3是否存在eleSet中:"+jedis.sismember("eleSet","e3"));
System.out.println("e1是否存在eleSet中:"+jedis.sismember("eleSet","e1"));
System.out.println("e5是否存在eleSet中:"+jedis.sismember("eleSet","e5"));
System.out.println("==============================");
System.out.println(jedis.sadd("eleSet1","e1","e0","e3","e6","e5","e7","e8"));
System.out.println(jedis.sadd("eleSet2","e1","e0","e3","e6","e8"));
System.out.println("將eleSet1刪除e1并存入eleSet3中:"+jedis.smove("eleSet1","eleSet3","e1"));
System.out.println("將eleSet1刪除e2并存入eleSet3中:"+jedis.smove("eleSet1","eleSet3","e2"));
System.out.println("eleSet1的所有元素為:"+jedis.smembers("eleSet1"));
System.out.println("eleSet3的所有元素為:"+jedis.smembers("eleSet3"));
System.out.println("================集合運(yùn)算===============");
System.out.println("eleSet1的所有元素為:"+jedis.smembers("eleSet1"));
System.out.println("eleSet2的所有元素為:"+jedis.smembers("eleSet2"));
System.out.println("eleSet1和eleSet2的交集:"+jedis.sinter("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的并集:"+jedis.sunion("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2"));
jedis.sinterstore("eleSet4","eleSet1","eleSet2");//求交集并保存到eleSet4中
System.out.println("eleSet4的所有元素為:"+jedis.smembers("eleSet4"));
jedis.close();
}
}


(5)Hash
package com.hcz;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.Map;
public class TestHash {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
Map<String,String> map = new HashMap<>();
map.put("key1","v1");
map.put("key2","v2");
map.put("key3","v3");
map.put("key4","v4");
//添加名稱為hash的hash元素
jedis.hmset("hash",map);
//向名稱為hash的hash中添加key為key5,value為v5元素
jedis.hset("hash","key5","v5");
System.out.println("散列hash的所有鍵值對(duì)為:"+jedis.hgetAll("hash"));
System.out.println("散列hash的所有鍵為:"+jedis.hkeys("hash"));
System.out.println("散列hash的所有值為:"+jedis.hvals("hash"));
System.out.println("將key6保存的值加上一個(gè)整數(shù),如果key6不存在則添加key6:"+jedis.hincrBy("hash","key6",4));
System.out.println("散列hash的所有鍵值對(duì)為:"+jedis.hgetAll("hash"));
System.out.println("刪除一個(gè)或者多個(gè)鍵值對(duì):"+jedis.hdel("hash","key2","key4"));
System.out.println("散列hash的所有鍵值對(duì)為:"+jedis.hgetAll("hash"));
System.out.println("散列hash的所有鍵值對(duì)個(gè)數(shù)為:"+jedis.hlen("hash"));
System.out.println("判斷hash中是否存在key2:"+jedis.hexists("hash","key2"));
System.out.println("判斷hash中是否存在key3:"+jedis.hexists("hash","key3"));
System.out.println("獲取hash中的值:"+jedis.hget("hash","key3"));
System.out.println("獲取hash中的值:"+jedis.hmget("hash","key3","key5"));
jedis.close();
}
}

5、Jedis實(shí)現(xiàn)事務(wù)
(1)事務(wù)正常執(zhí)行
public class TestMulti {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello","world");
jsonObject.put("name","hcz");
//開啟事務(wù)
Transaction multi = jedis.multi();
String result = jsonObject.toJSONString();
try {
multi.set("user1",result);
multi.set("user2",result);
multi.exec();//執(zhí)行事務(wù)
}catch (Exception e){
multi.discard();//放棄事務(wù)
e.printStackTrace();
}finally {
System.out.println("user1為:"+jedis.get("user1"));
System.out.println("user2為:"+jedis.get("user2"));
jedis.close();//關(guān)閉連接
}
}
}

(2)事務(wù)編譯時(shí)異常
public class TestMulti {
public static void main(String[] args) {
Jedis jedis = new Jedis("49.236.195.225",6379);
System.out.println("連接成功:"+jedis.ping());
System.out.println("清空數(shù)據(jù):"+jedis.flushDB());
JSONObject jsonObject = new JSONObject();
jsonObject.put("hello","world");
jsonObject.put("name","hcz");
//開啟事務(wù)
Transaction multi = jedis.multi();
String result = jsonObject.toJSONString();
try {
multi.set("user1",result);
multi.set("user2",result);
int i = 1/0;//代碼拋出異常事務(wù),執(zhí)行失敗
multi.exec();//執(zhí)行事務(wù)
}catch (Exception e){
multi.discard();//放棄事務(wù)
e.printStackTrace();
}finally {
System.out.println("user1為:"+jedis.get("user1"));
System.out.println("user2為:"+jedis.get("user2"));
jedis.close();//關(guān)閉連接
}
}
}

二、整合SpringBoot
1、導(dǎo)入依賴
說(shuō)明:
在SpringBoot2.x之后,原來(lái)使用的jedis被替換為了lettuce
jedis:采用直連,多個(gè)線程操作的話是不安全的,如果想要避免不安全,可以使用 jedis pool連接池!更像BIO模式lettuce:采用netty,實(shí)例可以再多個(gè)線程共享,不存在線程不安全的情況,可以減少線程數(shù)據(jù)!更像NIO模式
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置連接
spring:
redis:
host: 49.236.195.225 #遠(yuǎn)程主機(jī)名
port: 6379 #端口號(hào)
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 500
min-idle: 0
lettuce:
shutdown-timeout: 0ms
3、測(cè)試連接
@SpringBootTest
class SpringbootRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
//redisTemplate
//opsForValue 操作字符串 類似String
//opsForList 操作List 類型List
//opsForSet
//opsForHash
//opsForZSet
//opsForGeo
//opsForHyperLogLog
//獲取連接對(duì)象
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushDb();
//connection.flushAll();
redisTemplate.opsForValue().set("myKey","myValue");
System.out.println(redisTemplate.opsForValue().get("myKey"));
}
}

4、序列化
@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
//在企業(yè)中,我們所有的pojo都會(huì)序列化
public class User implements Serializable {
private String name;
private int age;
}
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test(){
try {
//真實(shí)開發(fā)一般使用json來(lái)傳遞對(duì)象
User user = new User("張三 ", 18);
//String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",user);
System.out.println(redisTemplate.opsForValue().get("user"));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}

5、自定義序列化
@Configuration
public class RedisConfig {
//自定義了一個(gè)RedisTemplate
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
//為了開發(fā)方便,一般使用<String, Object>
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
//Json序列化配置
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);
//String的序列化
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;
}
}
6、自定義工具類
自定義工具類的好處:
已經(jīng)幫我們將原生的redisTemplate.opsForValue().set() 復(fù)雜命令封裝成一些簡(jiǎn)單的命令
@Component
public final class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================
/**
* 指定緩存失效時(shí)間
* @param key 鍵
* @param time 時(shí)間(秒)
*/
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;
}
}
…………省略后面一大堆代碼…………
7、再次進(jìn)行測(cè)試
@Autowired
private RedisUtil redisUtil;
@Test
public void test2(){
redisUtil.set("username","hcz");
System.out.println(redisUtil.get("username"));
redisUtil.hset("hash","age",18);
System.out.println(redisUtil.hget("hash","age"));
redisUtil.hincr("hash","age",5);
System.out.println(redisUtil.hget("hash","age"));
}

到此這篇關(guān)于遠(yuǎn)程連接Jedis和整合SpringBoot的詳細(xì)過(guò)程的文章就介紹到這了,更多相關(guān)Jedis和SpringBoot整合內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java通過(guò)IO流輸出文件目錄的實(shí)例代碼
這篇文章主要介紹了Java通過(guò)IO流輸出文件目錄,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
Java線程池流程編排運(yùn)用實(shí)戰(zhàn)源碼
這篇文章主要介紹了Java線程池流程編排運(yùn)用實(shí)戰(zhàn)源碼,就在流程引擎的基礎(chǔ)上運(yùn)用?ThreadPoolExecutor,使用線程池實(shí)現(xiàn)?SpringBean?的異步執(zhí)行2022-03-03
springmvc處理模型數(shù)據(jù)Map過(guò)程解析
這篇文章主要介紹了springmvc處理模型數(shù)據(jù)Map過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
SpringBoot項(xiàng)目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫(kù)的過(guò)程
SQLite是一個(gè)緊湊的庫(kù),啟用所有功能后,庫(kù)大小可以小于 750KiB, 具體取決于目標(biāo)平臺(tái)和編譯器優(yōu)化設(shè)置, 內(nèi)存使用量和速度之間需要權(quán)衡,這篇文章主要介紹了SpringBoot項(xiàng)目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫(kù),需要的朋友可以參考下2024-07-07
JAVA內(nèi)存模型和Happens-Before規(guī)則知識(shí)點(diǎn)講解
在本篇文章里小編給大家整理的是一篇關(guān)于JAVA內(nèi)存模型和Happens-Before規(guī)則知識(shí)點(diǎn)內(nèi)容,有需要的朋友們跟著學(xué)習(xí)下。2020-11-11
初識(shí)sa-token及登錄授權(quán)簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要為大家介紹了sa-token及登錄授權(quán)簡(jiǎn)單實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07

