服务器之家

服务器之家 > 正文

远程连接Jedis和整合SpringBoot的详细过程

时间:2021-12-01 13:03     来源/作者:@烟雨倾城ゝ

一、远程连接jedis

1、导入jedis所需的jar包

?
1
2
3
4
5
6
7
8
9
10
11
<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、远程连接redis注意事项

  • 禁用linux的防火墙:systemctl stop/disable firewalld.service
  • 在配置文件redis.conf中注释掉bind 127.0.0.1 ,然后修改protected-mode no

3、jedis测试远程连接

?
1
2
3
4
5
6
7
8
9
10
11
12
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();
    }
}

远程连接Jedis和整合SpringBoot的详细过程

4、常用的数据类型

(1)key

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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();
    }
}

远程连接Jedis和整合SpringBoot的详细过程

(2)string

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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();
    }
}

远程连接Jedis和整合SpringBoot的详细过程

远程连接Jedis和整合SpringBoot的详细过程

(3)list

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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();
    }
}

远程连接Jedis和整合SpringBoot的详细过程

(4)set

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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();
    }
}

远程连接Jedis和整合SpringBoot的详细过程

远程连接Jedis和整合SpringBoot的详细过程

(5)hash

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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();
    }
}

远程连接Jedis和整合SpringBoot的详细过程

5、jedis实现事务

(1)事务正常执行

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();//关闭连接
        }
 
    }
}

远程连接Jedis和整合SpringBoot的详细过程

(2)事务编译时异常

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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();//关闭连接
        }
 
    }
}

远程连接Jedis和整合SpringBoot的详细过程

二、整合springboot

1、导入依赖

说明:

在springboot2.x之后,原来使用的jedis被替换为了lettuce

jedis:采用直连,多个线程操作的话是不安全的,如果想要避免不安全,可以使用 jedis pool连接池!更像bio模式lettuce:采用netty,实例可以再多个线程共享,不存在线程不安全的情况,可以减少线程数据!更像nio模式
?
1
2
3
4
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

2、配置连接

?
1
2
3
4
5
6
7
8
9
10
11
12
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

3、测试连接

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@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"));
    }
 
}

远程连接Jedis和整合SpringBoot的详细过程

4、序列化

?
1
2
3
4
5
6
7
8
9
10
@component
@allargsconstructor
@noargsconstructor
@data
//在企业中,我们所有的pojo都会序列化
public class user implements serializable {
 
    private string name;
    private int age;
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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();
    }
 
 
}

远程连接Jedis和整合SpringBoot的详细过程

5、自定义序列化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@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;
  }
}

6、自定义工具类

自定义工具类的好处

已经帮我们将原生的redistemplate.opsforvalue().set() 复杂命令封装成一些简单的命令

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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、再次进行测试

?
1
2
3
4
5
6
7
8
9
10
11
12
@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和整合SpringBoot的详细过程

到此这篇关于远程连接jedis和整合springboot的详细过程的文章就介绍到这了,更多相关jedis和springboot整合内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/hcz666/article/details/119845922

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部