java redisCluster

一:redisson和 redisCluster性能对比

组件 操作 数量 耗时(ms)
jediscluster hset 100000 213959
jediscluster hget 100000 228830
jediscluster hdel 100000
       
redisson hset 100000 116167
redisson hget 100000 37631
redisson hdel 100000

二:java redisCluster单元测试

1:src/main/resources/redis.properties

cluster1.host.port=192.168.18.37:7000
cluster2.host.port=192.168.18.37:7001
cluster3.host.port=192.168.18.37:7002
cluster4.host.port=192.168.18.37:7003
cluster5.host.port=192.168.18.37:7004
cluster6.host.port=192.168.18.37:7005
redis.scanInterval=10000


redis.maxIdle=100  
redis.maxActive=300  
redis.maxWait=1000  
redis.timeout=100000  
redis.maxTotal=1000  
redis.minIdle=8  
redis.testOnBorrow=true 

2:src/main/resources/redis.properties/spring-context.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.0.xsd
    ">
    
    <context:component-scan base-package="com.niiwoo.rce.module.redis" />


    <bean id="propertyConfigurer"  
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:redis.properties" />  
    </bean> 
    
 <!-- jedis 配置-->  
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" >  
        <!--最大空闲数-->  
        <property name="maxIdle" value="${redis.maxIdle}" />  
        <!--最大建立连接等待时间-->  
        <property name="maxWaitMillis" value="${redis.maxWait}" />  
        <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->  
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
        <property name="maxTotal" value="${redis.maxTotal}" />  
        <property name="minIdle" value="${redis.minIdle}" />  
    </bean >  
    
    <bean id="jedisCluster"  class="com.niiwoo.rce.jediscluster.JedisClusterFactory" >  
        <property name="addressConfig">  
            <value>classpath:redis.properties</value>  
        </property>  
        <property name="addressKeyPrefix" value="cluster" />   <!--  属性文件里  key的前缀 -->  
        <property name="timeout" value="300000" />  
        <property name="maxRedirections" value="6" />  
        <property name="genericObjectPoolConfig" ref="poolConfig" />  
    </bean >  
    
    
       <bean id="mystudent"  class="com.niiwoo.rce.jediscluster.MyStudent" />  
    
    

</beans>


3: pom.xml依赖

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
</dependency>

4:

package com.niiwoo.rce.jediscluster;


import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;


import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;


import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;


public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean {  
    private Resource addressConfig;  
    private String addressKeyPrefix ;  
    private JedisCluster jedisCluster;  
    private Integer timeout;  
    private Integer maxRedirections;  
    private GenericObjectPoolConfig genericObjectPoolConfig;  
    private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");  
    @Override  
    public JedisCluster getObject() throws Exception {  
        return jedisCluster;  
    }  
    @Override  
    public Class<? extends JedisCluster> getObjectType() {  
        return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);  
    }  
    @Override  
    public boolean isSingleton() {  
        return true;  
    }  


    private Set<HostAndPort> parseHostAndPort() throws Exception {  
        try {  
            Properties prop = new Properties();  
            prop.load(this.addressConfig.getInputStream());  


            Set<HostAndPort> haps = new HashSet<HostAndPort>();  
            for (Object key : prop.keySet()) {  


                if (!((String) key).startsWith(addressKeyPrefix)) {  
                    continue;  
                }  


                String val = (String) prop.get(key);  


                boolean isIpPort = p.matcher(val).matches();  


                if (!isIpPort) {  
                    throw new IllegalArgumentException("ip 或 port 不合法");  
                }  
                String[] ipAndPort = val.split(":");  
                HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));  
                haps.add(hap);  
            }  


            return haps;  
        } catch (IllegalArgumentException ex) {  
        ex.printStackTrace();
            throw ex;  
        } catch (Exception ex) {  
            throw new Exception("解析 jedis 配置文件失败", ex);  
        }  
    }  


    @Override  
    public void afterPropertiesSet() throws Exception {  
        Set<HostAndPort> haps = this.parseHostAndPort();  
        jedisCluster = new JedisCluster(haps, timeout, maxRedirections,genericObjectPoolConfig);  
    }  
    public void setAddressConfig(Resource addressConfig) {  
        this.addressConfig = addressConfig;  
    }  


    public void setTimeout(int timeout) {  
        this.timeout = timeout;  
    }  


    public void setMaxRedirections(int maxRedirections) {  
        this.maxRedirections = maxRedirections;  
    }  


    public void setAddressKeyPrefix(String addressKeyPrefix) {  
        this.addressKeyPrefix = addressKeyPrefix;  
    }  


    public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {  
        this.genericObjectPoolConfig = genericObjectPoolConfig;  
    }  


}  


5:


package com.niiwoo.rce.jediscluster;


import java.util.UUID;


import org.junit.BeforeClass;
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.JedisCluster;


import com.niiwoo.rce.module.redis.RedisManager;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-context.xml")
public class JedeisClusterTest {


@BeforeClass
public static void init() {
System.out.println("system is init");
}

    @Autowired  
    private MyStudent myStudent;  


    @Test
    public void testJedisCluster(){
    myStudent.setName("www");
    myStudent.setAge(12);
        System.out.println("testJedisCluster");
      /*  myjedisCluster.set("name", "啊芝");
        String val = myjedisCluster.get("name");
        System.out.println(val);*/
    }
    
    @Autowired  
    private JedisCluster jedisCluster;  


    
@Autowired
private RedisManager redisManager;

@Test
public void testRedisManager() {

}


    @Test
    public void testJedisCluster1(){
   
//     jedisCluster.hset("sessionmap_2", key, "hisname5");
//     jedisCluster.hdel("sessionmap_2", key);
//     jedisCluster.hgetAll("sessionmap_2");
   
/*Map<String, String> maps = jedisCluster.hgetAll("sessionmap_2");
for (String s : maps.keySet()) {
System.out.println(s + "\t" + maps.get(s));
}*/


    long start=System.currentTimeMillis();
    String key = UUID.randomUUID().toString();
    redisManager.hset("sessionmap_2", key, key);
/*for (int i = 0; i < 10_0000; i++) {
String key = UUID.randomUUID().toString();
jedisCluster.hset("sessionmaIp_2", key, key);


}*/
   
    /*Map<String, String> maps = jedisCluster.hgetAll("sessionmap_2");
for (String key : maps.keySet()) {
jedisCluster.hdel("sessionmap_2", key);
}*/
   /* for (int i = 0; i < 10_0000;i++) {
   
    String key=UUID.randomUUID().toString();
    jedisCluster.hset("sessionmap_2", key, key);
   
}*/
    System.out.println("耗时:"+(System.currentTimeMillis()-start));
   
//     jedisCluster.hdel("sessionmap_2", "24c45f47-b8cf-4cf7-be9f-489a87e6397c");

//     jedisCluster.setnx(key, value)
//        jedisCluster.set("myname", "啊芝");
//        String val = jedisCluster.get("myname");
//        System.out.println("testJedisCluster1");
//        System.out.println(val);
    }
    
    
    
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 编写Redis cluster连接池需要使用Java客户端,例如Jedis,Lettuce等,并使用连接池管理器来管理连接。具体的实现可以参考Redisson的源码,它是一个开源的Redis Java连接池库。 ### 回答2: RedisClusterRedis的一个集群模式,它以分布式的方式存储数据,并提供高可用性和性能的读写操作。在使用Java连接RedisCluster时,可以使用JedisCluster对象进行连接管理并操作Redis集群。 下面是一个简单的示例,展示如何使用Java编写一个RedisCluster连接池: 1. 首先,我们需要在pom.xml中添加Jedis依赖: ```xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.10.0</version> </dependency> ``` 2. 创建RedisCluster连接池对象。可以使用Apache Commons Pool来实现一个连接池,用于管理连接的复用和分配等操作: ```java import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import java.util.HashSet; import java.util.Set; public class RedisClusterConnectionPool { private static final String HOST = "127.0.0.1"; private static final int PORT = 6379; private static final int CONNECTION_TIMEOUT = 2000; private static final int MAX_TOTAL_CONNECTIONS = 10; private static final int MAX_IDLE_CONNECTIONS = 5; private static final int MIN_IDLE_CONNECTIONS = 1; private static final long MAX_WAIT_TIME = 2000; private JedisCluster jedisCluster; public RedisClusterConnectionPool() { Set<HostAndPort> jedisClusterNodes = new HashSet<>(); jedisClusterNodes.add(new HostAndPort(HOST, PORT)); // 配置连接池 GenericObjectPoolConfig<JedisCluster> poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(MAX_TOTAL_CONNECTIONS); poolConfig.setMaxIdle(MAX_IDLE_CONNECTIONS); poolConfig.setMinIdle(MIN_IDLE_CONNECTIONS); poolConfig.setMaxWaitMillis(MAX_WAIT_TIME); // 创建连接池 GenericObjectPool<JedisCluster> connectionPool = new GenericObjectPool<>(new RedisClusterConnectionFactory(jedisClusterNodes), poolConfig); // 从连接池获取JedisCluster对象 try { jedisCluster = connectionPool.borrowObject(); } catch (Exception e) { e.printStackTrace(); } } } ``` 3. 创建RedisClusterConnectionFactory类,用于创建JedisCluster连接: ```java import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.Set; public class RedisClusterConnectionFactory implements PooledObjectFactory<JedisCluster> { private Set<HostAndPort> jedisClusterNodes; public RedisClusterConnectionFactory(Set<HostAndPort> jedisClusterNodes) { this.jedisClusterNodes = jedisClusterNodes; } @Override public PooledObject<JedisCluster> makeObject() throws Exception { return new DefaultPooledObject<>(new JedisCluster(jedisClusterNodes)); } @Override public void destroyObject(PooledObject<JedisCluster> p) throws Exception { p.getObject().close(); } @Override public boolean validateObject(PooledObject<JedisCluster> p) { return p.getObject().isConnected(); } @Override public void activateObject(PooledObject<JedisCluster> p) throws Exception { } @Override public void passivateObject(PooledObject<JedisCluster> p) throws Exception { } } ``` 以上就是一个使用Java编写的RedisCluster连接池的基本实现。通过这个连接池,我们可以方便地获取并管理RedisCluster的连接对象,以便进行各种读写操作。同时,连接池也提供了连接复用、性能优化等功能,提高了系统的可靠性和性能。 ### 回答3: Java RedisCluster连接池是一个用于管理Redis集群连接的工具,用于提高连接的复用性和性能。 首先,我们需要引入redis.clients.jedis.JedisCluster类作为Redis集群连接的核心类,并在项目中引入Jedis库。 接下来,我们可以创建一个RedisClusterPool类,该类包含以下几个主要方法: 1. 初始化连接池:在初始化方法中,我们可以通过配置文件或硬编码方式获取Redis集群的主机地址、端口号等信息,并创建一个连接池对象。在连接池对象中,我们可以设置最大连接数、最大空闲连接数、连接超时时间等参数。 2. 获取连接:通过getConnection方法,我们可以从连接池中获取一个可用的Redis连接。连接池管理多个连接对象,并根据需要进行创建、销毁和维护。 3. 释放连接:使用完Redis连接后,我们需要将连接释放回连接池,以供其他线程使用。通过releaseConnection方法,我们可以将连接归还到连接池中。 4. 关闭连接池:在程序结束时,需要显式地关闭连接池,以释放连接池所占用的资源。通过closePool方法,我们可以关闭连接池,并释放所有连接。 此外,我们还可以增加一些辅助方法,用于检查连接是否可用、重连失败的连接等。 使用Java编写RedisCluster连接池的好处是,可以有效地管理和复用Redis连接,提高系统性能和稳定性。同时,连接池可以减少重复创建和销毁连接的开销,并可以根据实际需求自动调整连接的创建和回收策略,提供更好的连接资源管理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值