1 查看支持Java的redis客户端

  本博文采用 Jedis 作为redis客户端,采用 commons-pool2 作为连接redis服务器的连接池

 

2 下载相关依赖与实战

  2.1 到 Repository 官网下载jar包

    jedis

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

   commons-pool2   

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.5.0</version>
</dependency>

  2.2 传统使用(eclipse)

    准备:创建一个普通的Java项目

    2.2.1 添加jar包

      在项目的根目录下创建一个lib文件夹,并将下载好的两个jar包添加到lib文件夹里面

      Redis02 Redis客户端之Java、连接远程Redis服务器失败

    2.2.2 将jar包添加到项目构建路径中

      选中lib中的jar包 -> 右键 -> build path -> add to build path

    2.2.3 在build path中查看

      项目文件夹 -> 右键 -> build path -> configure build path 

      Redis02 Redis客户端之Java、连接远程Redis服务器失败

      技巧01:也可以在 build path中进行添加【ps: 待添加的jar包可以在任何位置,不用将他们放到项目文件夹下的lib中,我这样做的目的是为了避免jar包被不小心删除掉】

  2.3 代码实现

    借助 Jedis 去对 Redis 进行操作

    技巧01:其实和操作MySQL的套路一样

    2.3.1 单实例模式

      就是不使用连接池的模式,每次要对 Redis 进行操作时先自己创建连接,在进行相关操作,操作完后自己在关闭连接;这样很消耗内存

    @Test
    public void test01() {
        System.out.println("Hello Boy");
        // 01 获取Jedis客户端【设置IP和端口】
        Jedis jedis = new Jedis("192.168.233.134", 6379);
        
        // 02 保存数据
        jedis.set("name", "王杨帅");
        
        // 03 获取数据
        String value = jedis.get("name");
        System.out.println("获取到的数据为:" + value);
        
        String age = jedis.get("age");
        System.out.println("获取到的年龄信息为:" + age);
        
        
        // 04 释放资源
        jedis.close();
        
    }
View Code

相关文章:

  • 2022-12-23
  • 2021-11-04
  • 2022-01-14
  • 2021-10-12
  • 2021-08-27
  • 2021-12-06
  • 2021-12-05
猜你喜欢
  • 2021-08-11
  • 2022-12-23
  • 2021-08-21
  • 2021-12-19
  • 2021-08-19
  • 2021-11-08
  • 2021-11-14
相关资源
相似解决方案