您好,登錄后才能下訂單哦!
本篇內容主要講解“怎么遠程連接Jedis”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么遠程連接Jedis”吧!
一、遠程連接Jedis
1、導入Jedis所需的jar包
2、遠程連接Redis注意事項
3、Jedis測試遠程連接
4、常用的數據類型
5、Jedis實現事務
二、整合SpringBoot
1、導入依賴
2、配置連接
3、測試連接
4、序列化
5、自定義序列化
6、自定義工具類
7、再次進行測試
<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>
禁用Linux的防火墻:systemctl stop/disable firewalld.service
在配置文件redis.conf中注釋掉bind 127.0.0.1 ,然后修改protected-mode no
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(); } }
(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("清空數據:"+jedis.flushDB()); System.out.println("判斷某個鍵知否存在:"+jedis.exists("username")); System.out.println("新增<'username','hcz'>的鍵值對"+jedis.set("username","hcz")); System.out.println("新增<'password','123'>的鍵值對"+jedis.set("password","123")); System.out.println("系統中所有的鍵如下:"); 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所存儲的值的類型:"+jedis.type("username")); System.out.println("隨機返回key空間的一個:"+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("清空當前數據庫所有的key:"+jedis.flushDB()); System.out.println("返回當前數據庫中key的數目:"+jedis.dbSize()); System.out.println("刪除所有數據庫中的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("清空數據:"+jedis.flushDB()); System.out.println("====增加數據===="); 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("增加多個鍵值對:"+jedis.mset("k4","v4","k5","v5")); System.out.println("獲取多個鍵值對:"+jedis.mget("k3","k4","k5")); System.out.println("刪除多個鍵值對:"+jedis.del("k1","k3")); System.out.println("清空數據:"+jedis.flushDB()); System.out.println("====新增鍵值對防止覆蓋原先值===="); 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("====新增鍵值并設置有效時間===="); 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("清空數據:"+jedis.flushDB()); System.out.println("====增加一個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的內容:"+jedis.lrange("collections",0,-1)); System.out.println("collections區間的0-3號元素:"+jedis.lrange("collections",0,3)); System.out.println("==========================="); //刪除指定的值,第二個參數為刪除的個數(有重復時),后add進去的值先被刪除,類似出棧 System.out.println("刪除指定元素個數"+jedis.lrem("collections",2,"HashMap")); System.out.println("collections的內容:"+jedis.lrange("collections",0,-1)); System.out.println("collections列表出棧(左端):"+jedis.lpop("collections")); System.out.println("collections的內容:"+jedis.lrange("collections",0,-1)); System.out.println("collections添加元素,從列表右端,與lpush相對應:"+jedis.rpush("collections","List","Set","String")); System.out.println("collections的內容:"+jedis.lrange("collections",0,-1)); System.out.println("collections列表出棧(右端):"+jedis.rpop("collections")); System.out.println("collections的內容:"+jedis.lrange("collections",0,-1)); System.out.println("修改collections指定下標為1的內容:"+jedis.lset("collections",1,"newHashSet")); System.out.println("collections的內容:"+jedis.lrange("collections",0,-1)); System.out.println("==============================="); System.out.println("collections的長度:"+jedis.llen("collections")); System.out.println("獲取collections下標為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("清空數據:"+jedis.flushDB()); System.out.println("==========向集合中添加元素(不重復)"); 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("刪除一個元素e0:"+jedis.srem("eleSet","e0")); System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet")); System.out.println("刪除二個元素e7,e6:"+jedis.srem("eleSet","e7","e6")); System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet")); System.out.println("隨機的移除集合中的一個元素:"+jedis.spop("eleSet")); System.out.println("隨機的移除集合中的一個元素:"+jedis.spop("eleSet")); System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet")); System.out.println("eleSet的元素個數為:"+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("================集合運算==============="); 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("清空數據:"+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的所有鍵值對為:"+jedis.hgetAll("hash")); System.out.println("散列hash的所有鍵為:"+jedis.hkeys("hash")); System.out.println("散列hash的所有值為:"+jedis.hvals("hash")); System.out.println("將key6保存的值加上一個整數,如果key6不存在則添加key6:"+jedis.hincrBy("hash","key6",4)); System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash")); System.out.println("刪除一個或者多個鍵值對:"+jedis.hdel("hash","key2","key4")); System.out.println("散列hash的所有鍵值對為:"+jedis.hgetAll("hash")); System.out.println("散列hash的所有鍵值對個數為:"+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(); } }
(1)事務正常執行
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("清空數據:"+jedis.flushDB()); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello","world"); jsonObject.put("name","hcz"); //開啟事務 Transaction multi = jedis.multi(); String result = jsonObject.toJSONString(); try { multi.set("user1",result); multi.set("user2",result); multi.exec();//執行事務 }catch (Exception e){ multi.discard();//放棄事務 e.printStackTrace(); }finally { System.out.println("user1為:"+jedis.get("user1")); System.out.println("user2為:"+jedis.get("user2")); jedis.close();//關閉連接 } } }
(2)事務編譯時異常
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("清空數據:"+jedis.flushDB()); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello","world"); jsonObject.put("name","hcz"); //開啟事務 Transaction multi = jedis.multi(); String result = jsonObject.toJSONString(); try { multi.set("user1",result); multi.set("user2",result); int i = 1/0;//代碼拋出異常事務,執行失敗 multi.exec();//執行事務 }catch (Exception e){ multi.discard();//放棄事務 e.printStackTrace(); }finally { System.out.println("user1為:"+jedis.get("user1")); System.out.println("user2為:"+jedis.get("user2")); jedis.close();//關閉連接 } } }
說明:
在SpringBoot2.x之后,原來使用的jedis被替換為了lettuce
jedis:采用直連,多個線程操作的話是不安全的,如果想要避免不安全,可以使用 jedis pool連接池!更像BIO模式lettuce:采用netty,實例可以再多個線程共享,不存在線程不安全的情況,可以減少線程數據!更像NIO模式
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
spring: redis: host: 49.236.195.225 #遠程主機名 port: 6379 #端口號 jedis: pool: max-active: 8 max-wait: -1ms max-idle: 500 min-idle: 0 lettuce: shutdown-timeout: 0ms
@SpringBootTest class SpringbootRedisApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test void contextLoads() { //redisTemplate //opsForValue 操作字符串 類似String //opsForList 操作List 類型List //opsForSet //opsForHash //opsForZSet //opsForGeo //opsForHyperLogLog //獲取連接對象 RedisConnection connection = redisTemplate.getConnectionFactory().getConnection(); connection.flushDb(); //connection.flushAll(); redisTemplate.opsForValue().set("myKey","myValue"); System.out.println(redisTemplate.opsForValue().get("myKey")); } }
@Component @AllArgsConstructor @NoArgsConstructor @Data //在企業中,我們所有的pojo都會序列化 public class User implements Serializable { private String name; private int age; }
@Autowired private RedisTemplate redisTemplate; @Test public void test(){ try { //真實開發一般使用json來傳遞對象 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(); } }
@Configuration public class RedisConfig { //自定義了一個RedisTemplate @Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { //為了開發方便,一般使用<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; } }
自定義工具類的好處:
已經幫我們將原生的redisTemplate.opsForValue().set() 復雜命令封裝成一些簡單的命令
@Component public final class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; // =============================common============================ /** * 指定緩存失效時間 * @param key 鍵 * @param time 時間(秒) */ 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; } } …………省略后面一大堆代碼…………
@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")); }
到此,相信大家對“怎么遠程連接Jedis”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。