Java集成redis集群

spring-redis.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-4.1.xsd">

    <!-- jedis cluster config -->
    <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig" >
        <property name="maxWaitMillis" value="-1" />
        <property name="maxTotal" value="1000" />
        <property name="minIdle" value="8" />
        <property name="maxIdle" value="100" />
    </bean>

    <bean id="jedisCluster" class="qgs.npms.redis.JedisClusterFactory">
        <property name="addressConfig">
            <value>classpath:/redis/redis-config.properties</value>
        </property>
        <property name="addressKeyPrefix" value="address" />

        <property name="timeout" value="300000" />
        <property name="maxRedirections" value="6" />
        <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" />
    </bean>
</beans>
自己创建一个类JedisClusterFactory:
import java.util.HashSet;
import java.util.Iterator;
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*$");

    public JedisClusterFactory() {
    }

    public JedisCluster getObject() throws Exception {
        return this.jedisCluster;
    }

    public Class<? extends JedisCluster> getObjectType() {
        return this.jedisCluster != null?this.jedisCluster.getClass():JedisCluster.class;
    }

    public boolean isSingleton() {
        return true;
    }

    private Set<HostAndPort> parseHostAndPort() throws Exception {
        try {
            Properties ex = new Properties();
            ex.load(this.addressConfig.getInputStream());
            HashSet haps = new HashSet();
            Iterator i$ = ex.keySet().iterator();

            while(i$.hasNext()) {
                Object key = i$.next();
                if(((String)key).startsWith(this.addressKeyPrefix)) {
                    String val = (String)ex.get(key);
                    boolean isIpPort = this.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 var9) {
            throw var9;
        } catch (Exception var10) {
            throw new Exception("解析 jedis 配置文件失败", var10);
        }
    }

    public void afterPropertiesSet() throws Exception {
        Set haps = this.parseHostAndPort();
        this.jedisCluster = new JedisCluster(haps, this.timeout.intValue(), this.maxRedirections.intValue(), this.genericObjectPoolConfig);
    }

    public void setAddressConfig(Resource addressConfig) {
        this.addressConfig = addressConfig;
    }

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

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

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

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

redis-config.properties:

address1=192.168.1.36:6379
address2=192.168.1.37:6379
address3=192.168.1.38:6379
address4=192.168.1.40:6379
address5=192.168.1.41:6379
address6=192.168.1.42:6379

Java调用:

@Autowiredprivate JedisCluster jedisCluster;  //jedisCluster就是对应的bean id 可以自动注入
System.out.println(jedisCluster.get("foo"));System.out.println(jedisCluster.set("qq","222"));System.out.println(jedisCluster.get("qq"));
时间: 2024-10-31 16:10:53

Java集成redis集群的相关文章

Spring集成redis集群

Spring集成redis集群 有密码 Maven <jedis.version>2.9.0</jedis.version> <spring-data-redis.version>1.7.1.RELEASE</spring-data-redis.version> <spring.version>3.2.17.RELEASE</spring.version> <dependency> <groupId>org.s

java操作redis集群配置[可配置密码]和工具类

java操作redis集群配置[可配置密码]和工具类 <dependency>   <groupId>redis.clients</groupId>   <artifactId>jedis</artifactId>   <version>2.9.0</version>   </dependency>   <dependency>   <groupId>org.apache.commons

突破Java面试-Redis集群模式的原理

1 面试题 Redis集群模式的工作原理说一下?在集群模式下,key是如何寻址的?寻址都有哪些算法?了解一致性hash吗? 2 考点分析 Redis不断在发展-Redis cluster集群模式,可以做到在多台机器上,部署多个实例,每个实例存储一部分的数据,同时每个实例可以带上Redis从实例,自动确保说,如果Redis主实例挂了,会自动切换到redis从实例顶上来. 现在新版本,大家都是用Redis cluster的,也就是原生支持的集群模式,那么面试官肯定会就redis cluster对你来

SpingBoot之集成Redis集群

一.安装Redis集群 安装步骤参照网上教程,Mac安装步骤参照https://github.com/muyl/mac-docker-redis-cluster 二.创建SpringBoot工程 创建Redis配置类 package com.example.chapterredis.common.config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.slf4j.Logger; import

Java操作 Redis 集群

// 连接redis集群 @Test public void testJedisCluster() { JedisPoolConfig config = new JedisPoolConfig(); // 最大连接数 config.setMaxTotal(30); // 最大连接空闲数 config.setMaxIdle(2); //集群结点 Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisC

java 连接 redis集群时报错:Could not get a resource from the pool

由于弄这个的时候浪费了太多的时间,所以才记录下这个错,给大伙参考下 检查了一下,配置啥的都没问题的,但在redis集群机器上就可以,错误如下: Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool 原因: 是因为我在创集群的时候的ip地址是:127.0.0.1,不是本机的电脑访问的话是不能访问的,

Springboot2.X集成redis集群(Lettuce)连接

前提:搭建好redis集群环境,搭建方式请看:https://www.cnblogs.com/xymBlog/p/9300574.html 1. 新建工程,pom.xml文件中添加redis支持 <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-data-redis</artifactId></depend

java操作 redis集群

1.redis服务端集群搭建步骤: 1.下载redis安装包,进行解压安装 2.安装ruby.rubygems install ruby ,安装ruby的原因是,在进行集群的时候,使用的是ruby语言工具实现的,所以在集群之前首先需要搭建ruby的环境 3.在上述步骤完成之后,便可以搭建集群环境,redis提供了两种集群搭建方法,执行脚本方法(安装包下面的util包中)和手动搭建. 注意: 1.在集群的时候,如果是远端客户端访问redis服务端,那么在分片的时候,需要使用Ip进行分片,下面会详细

java连接redis集群

http://m.blog.csdn.net/koushr/article/details/50956870 连接redis数据库(非集群模式) public static void main(String[] args) { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大连接数 poolConfig.setMaxTotal(2); // 最大空闲数 poolConfig.setMaxIdle(2); // 最大允许等待时间,如