JAVA连接Redis客户端多种方式实现

JAVA连接Redis客户端多种方式实现Jedis介绍Redis不仅使用命令来操作,而且可以使用程序客户端操作。现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、Node.js、Go等。在官方网站里列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis、等其中官方推荐使用Jedis和Redisson。Jedis同样也是托管在github上,地址:https://github.com/xetorthio/jedis<dependencies>..

大家好,又见面了,我是你们的朋友全栈君。

Jedis介绍
Redis不仅使用命令来操作,而且可以使用程序客户端操作。现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、Node.js、Go等。
在官方网站里列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis、等其中官方推荐使用Jedis和Redisson。 
Jedis同样也是托管在github上,地址:https://github.com/xetorthio/jedis
 

 <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <!-- 单元测试Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <!-- 配置Maven的JDK编译级别 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

单实例连接
 

 @Test
    public void testJedis() {
        //创建一个Jedis的连接
        Jedis jedis = new Jedis("10.28.184.25", 6379);
        //执行redis命令
        jedis.set("mytest", "hello world, this is jedis client!");
        //从redis中取值
        String result = jedis.get("mytest");
        //打印结果
        System.out.println(result);
        //关闭连接
        jedis.close();
    }

连接池连接
 

 @Test
    public void testJedisPool() {
        //创建一连接池对象
        JedisPool jedisPool = new JedisPool("10.28.184.25", 6379);
        //从连接池中获得连接
        Jedis jedis = jedisPool.getResource();
        String result = jedis.get("mytest") ;
        System.out.println(result);
        //关闭连接
        jedis.close();
        //关闭连接池
        jedisPool.close();
    }

连接redis集群
 

@Test
    public void testJedisCluster() throws Exception {
        //创建一连接,JedisCluster对象,在系统中是单例存在
        Set<HostAndPort> nodes = new HashSet<>();
        nodes.add(new HostAndPort("10.28.184.25", 7001));
        nodes.add(new HostAndPort("10.28.184.25", 7002));
        nodes.add(new HostAndPort("10.28.184.25", 7003));
        nodes.add(new HostAndPort("10.28.184.25", 7004));
        JedisCluster cluster = new JedisCluster(nodes);
        //执行JedisCluster对象中的方法,方法和redis一一对应。
        cluster.set("cluster-test", "my jedis cluster test");
        String result = cluster.get("cluster-test");
        System.out.println(result);
        //程序结束时需要关闭JedisCluster对象
        cluster.close();
    }

Jedis整合spring
配置spring配置文件applicationContext.xml
 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 连接池配置 -->
    <bean id="jedisPoolConfig"
          class="redis.clients.jedis.JedisPoolConfig">
        <!-- 最大连接数 -->
        <property name="maxTotal" value="30" />
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="10" />
        <!-- 每次释放连接的最大数目 -->
        <property name="numTestsPerEvictionRun" value="1024" />
        <!-- 释放连接的扫描间隔(毫秒) -->
        <property name="timeBetweenEvictionRunsMillis" value="30000" />
        <!-- 连接最小空闲时间 -->
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
        <property name="softMinEvictableIdleTimeMillis" value="10000" />
        <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
        <property name="maxWaitMillis" value="1500" />
        <!-- 在获取连接的时候检查有效性, 默认false -->
        <property name="testOnBorrow" value="true" />
        <!-- 在空闲时检查有效性, 默认false -->
        <property name="testWhileIdle" value="true" />
        <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
        <property name="blockWhenExhausted" value="false" />
    </bean>
    <!-- redis单机 通过连接池 -->
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool"
          destroy-method="close">
        <constructor-arg name="poolConfig"
                         ref="jedisPoolConfig" />
        <constructor-arg name="host" value="10.28.184.25" />
        <constructor-arg name="port" value="6379" />
    </bean>
    <!-- redis集群 -->
    <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
        <constructor-arg index="0">
            <set>
                <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg index="0" value="10.28.184.25"></constructorarg>
                    <constructor-arg index="1" value="7001"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg index="0" value="10.28.184.25"></constructorarg>
                    <constructor-arg index="1" value="7002"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg index="0" value="10.28.184.25"></constructorarg>
                    <constructor-arg index="1" value="7003"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg index="0" value="10.28.184.25"></constructorarg>
                    <constructor-arg index="1" value="7004"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg index="0" value="10.28.184.25"></constructorarg>
                    <constructor-arg index="1" value="7005"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg index="0" value="10.28.184.25"></constructorarg>
                    <constructor-arg index="1" value="7006"></constructor-arg>
                </bean>
            </set>

        </constructor-arg>
        <constructor-arg index="1" ref="jedisPoolConfig"></constructor-arg>
    </bean>
</beans>
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;

/**
 * @author wangbh
 * @Description: test1
 * @date 2021/12/8 10:00
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application.xml")
public class TestJedis2 {
    @Autowired
    private JedisPool jedisPool;
    @Resource
    private JedisCluster cluster;
    @Test
    public void testJedisPool() {
        // 从连接池中获得连接
        Jedis jedis = jedisPool.getResource();
        String result = jedis.get("mytest");
        System.out.println(result);
        // 关闭连接
        jedis.close();
    }
    @Test
    public void testJedisCluster() throws Exception {
        // 执行JedisCluster对象中的方法,方法和redis一一对应。
        cluster.set("cluster-test", "my jedis cluster test");
        String result = cluster.get("cluster-test");
        System.out.println(result);
    }
}
Redisson方式
package com;

import org.redisson.Redisson;
import org.redisson.config.Config;

/**
 * @author wangbh
 * @Description: test
 * @date 2021/8/19 10:44
 */
public class RedissonManager {
    private static Config config = new Config();
    //声明redisso对象
    private static Redisson redisson = null;

    //实例化redisson
    static {
        //单个
        config.useSingleServer().setPassword("!QAZxsw2#EDC(0Ol1)")
                .setAddress("192.168.1.239:6379").setDatabase(2);
        //        config.useClusterServers()
         集群状态扫描间隔时间,单位是毫秒
        //                .setScanInterval(2000)
        cluster方式至少6个节点(3主3从,3主做sharding,3从用来保证主宕机后可以高可用)
        //                .addNodeAddress("192.168.1.239:6379").setPassword("!QAZxsw2#EDC(0Ol1)");
        //得到redisson对象
        redisson = (Redisson) Redisson.create(config);
    }

    //获取redisson对象的方法
    public static Redisson getRedisson() {
        return redisson;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/132974.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • allow_url_fopen与安全以及PHP libcurl

    allow_url_fopen与安全以及PHP libcurl  allow_url_fopen=ON常常会给服务器和管理员带来麻烦,但是经常性(至少我这样认为)的我们需要远程读取某个东西,如果设置allow_url_fopen=OFF将其关闭,我们就没有办法远程读取。  幸好我们有一个很好的PHP模块–curl。下面我就以一个例子说说我用curl远程读取的方法:  第一,allow_url_fopen=ON的情况下:

    2022年7月21日
    10
  • 溜着弯儿就能黑掉身边的人,他是怎么做到的?

    溜着弯儿就能黑掉身边的人,他是怎么做到的?

    2022年3月7日
    34
  • Windows 编程(多进程)

    Windows编程(多进程)进程组成:操作系统用来管理进行的内核对象内核对象也是系统用来存放关于进程的统计信息的地方.内核对象是操作系统内部分配的一个内存块,该内存块是一种数据结构,其成员负

    2021年12月13日
    53
  • Python解释器以及PyCharm的安装

    Python解释器以及PyCharm的安装通过CSDN上,大神写的教程,安装了PyCharm,现自己总结Python解释器安装以及PyCharm安装过程。一、Python解释器安装解释器(英语:Interpreter),又译为直译器,是一种电脑程序能够把高级编程语言一行一行直接转译运行。解释器不会一次把整个程序转译出来,只像一位“中间人”,每次运行程序时都要先转成另一种语言再作运行,因此解释器的程序运行速度比较缓慢。它每转译一行程序叙述就…

    2022年7月22日
    6
  • 第一章 语音信号处理概述

    第一章 语音信号处理概述一、语音交互语音交互(VUI:VoiceUserInterface)是指人与人或者人与设备通过自然语音进行信息传递的过程。语音交互的优势输入效率高:相对于键盘输入,语音输入的速度是传统输入方式的3倍以上(有权威统计分析得到的数据)。语音检索效率高;可跨空间,也称为远程语音交互,至少一米以上;指令可组合,比如:看一部周星驰的电影,评分8分以上。 解放双手和双眼,更安全:如车载系统的语音点播和语音导航场景(不可能一般用手开车,一边用手点播音乐);比如医疗场景,医生可以一边动手术,一边口语记录病.

    2022年5月9日
    37
  • 初等数论–二次剩余与二次同余方程–二次互反律「建议收藏」

    初等数论–二次剩余与二次同余方程–二次互反律「建议收藏」信息安全数学基础–二次剩余与二次同余方程–雅可比符号Jacobisymbol博主是初学信息安全数学基础(整除+同余+原根+群环域),本意是想整理一些较难理解的定理、算法,加深记忆也方便日后查找;如果有错,欢迎指正。…

    2025年7月13日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号