溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么遠(yuǎn)程連接Jedis

發(fā)布時間:2021-08-23 20:02:18 來源:億速云 閱讀:127 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“怎么遠(yuǎn)程連接Jedis”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“怎么遠(yuǎn)程連接Jedis”吧!

目錄
  • 一、遠(yuǎn)程連接Jedis

    • 1、導(dǎo)入Jedis所需的jar包

    • 2、遠(yuǎn)程連接Redis注意事項(xiàng)

    • 3、Jedis測試遠(yuǎn)程連接

    • 4、常用的數(shù)據(jù)類型

    • 5、Jedis實(shí)現(xiàn)事務(wù)

  • 二、整合SpringBoot

    • 1、導(dǎo)入依賴

    • 2、配置連接

    • 3、測試連接

    • 4、序列化

    • 5、自定義序列化

    • 6、自定義工具類

    • 7、再次進(jìn)行測試

一、遠(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測試遠(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();
    }
}

怎么遠(yuǎn)程連接Jedis

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("判斷某個鍵知否存在:"+jedis.exists("username"));
        System.out.println("新增<'username','hcz'>的鍵值對"+jedis.set("username","hcz"));
        System.out.println("新增<'password','123'>的鍵值對"+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所存儲的值的類型:"+jedis.type("username"));

        System.out.println("隨機(jī)返回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("清空當(dāng)前數(shù)據(jù)庫所有的key:"+jedis.flushDB());
        System.out.println("返回當(dāng)前數(shù)據(jù)庫中key的數(shù)目:"+jedis.dbSize());
        System.out.println("刪除所有數(shù)據(jù)庫中的key:"+jedis.flushAll());

        jedis.close();
    }
}

怎么遠(yuǎn)程連接Jedis

(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("增加多個鍵值對:"+jedis.mset("k4","v4","k5","v5"));
        System.out.println("獲取多個鍵值對:"+jedis.mget("k3","k4","k5"));
        System.out.println("刪除多個鍵值對:"+jedis.del("k1","k3"));

        System.out.println("清空數(shù)據(jù):"+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("====新增鍵值并設(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();
    }
}

怎么遠(yuǎn)程連接Jedis

怎么遠(yuǎn)程連接Jedis

(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("====增加一個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號元素:"+jedis.lrange("collections",0,3));
        System.out.println("===========================");
        //刪除指定的值,第二個參數(shù)為刪除的個數(shù)(有重復(fù)時),后add進(jìn)去的值先被刪除,類似出棧
        System.out.println("刪除指定元素個數(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相對應(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的長度:"+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();
    }
}

怎么遠(yuǎn)程連接Jedis

(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("刪除一個元素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("隨機(jī)的移除集合中的一個元素:"+jedis.spop("eleSet"));
        System.out.println("隨機(jī)的移除集合中的一個元素:"+jedis.spop("eleSet"));
        System.out.println("eleSet的所有元素為:"+jedis.smembers("eleSet"));
        System.out.println("eleSet的元素個數(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();
    }
}

怎么遠(yuǎn)程連接Jedis

怎么遠(yuǎn)程連接Jedis

(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的所有鍵值對為:"+jedis.hgetAll("hash"));
        System.out.println("散列hash的所有鍵為:"+jedis.hkeys("hash"));
        System.out.println("散列hash的所有值為:"+jedis.hvals("hash"));
        System.out.println("將key6保存的值加上一個整數(shù),如果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的所有鍵值對個數(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();
    }
}

怎么遠(yuǎn)程連接Jedis

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)閉連接
        }

    }
}

怎么遠(yuǎn)程連接Jedis

(2)事務(wù)編譯時異常

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)閉連接
        }

    }
}

怎么遠(yuǎn)程連接Jedis

二、整合SpringBoot

1、導(dǎo)入依賴

說明:

在SpringBoot2.x之后,原來使用的jedis被替換為了lettuce

jedis:采用直連,多個線程操作的話是不安全的,如果想要避免不安全,可以使用 jedis pool連接池!更像BIO模式lettuce:采用netty,實(shí)例可以再多個線程共享,不存在線程不安全的情況,可以減少線程數(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	#端口號
      jedis:
        pool:
          max-active: 8
          max-wait: -1ms
          max-idle: 500
          min-idle: 0
      lettuce:
        shutdown-timeout: 0ms

3、測試連接

@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"));
    }

}

怎么遠(yuǎn)程連接Jedis

4、序列化

@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
//在企業(yè)中,我們所有的pojo都會序列化
public class User implements Serializable {

    private String name;
    private int age;
}
@Autowired
private RedisTemplate redisTemplate;	

@Test
public void test(){

    try {
        //真實(shí)開發(fā)一般使用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();
    }


}

怎么遠(yuǎn)程連接Jedis

5、自定義序列化

@Configuration
public class RedisConfig {

    //自定義了一個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ù)雜命令封裝成一些簡單的命令

@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;
        }
    }

…………省略后面一大堆代碼…………

7、再次進(jìn)行測試

@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"));
}

怎么遠(yuǎn)程連接Jedis

到此,相信大家對“怎么遠(yuǎn)程連接Jedis”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI