Java redis线程池(哨兵模式和集群模式)

@羲凡——只为了更好的活着

Java redis线程池(哨兵模式和集群模式)

0.前提准备

pom.xml文件中要添加依赖(根据自己的flink版本修改哈)

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>
1.Redis 哨兵模式 操作工具类
package redis;

import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

public class RedisSentinelUtil {
    private static final Logger LOG = LoggerFactory.getLogger(RedisSentinelUtil.class);
    // 最大连接实例的最大数目(默认值8)
    private static int MAX_TOTAL = -1;
    // 最多有多少个状态为idle(空闲的)的jedis实例(默认值8)
    private static int MAX_IDLE = 300;
    // 连接的最大时间,单位毫秒
    private static int MAX_WAIT = 3 * 1000;
    private static int MIN_IDLE = 100;
    private static JedisSentinelPool redisSentinelJedisPool = null;

    // 获取Jedis线程池
    public static synchronized void getPool(String clusterName, String addr, String auth) {
        if (redisSentinelJedisPool == null) {
            String[] hostAndPorts = addr.split(",");
            Set<String> sentinels = new HashSet<String>();
            for (String string : hostAndPorts) {
                sentinels.add(string);
            }
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_TOTAL); //最大连接数, 默认8
            config.setMaxIdle(MAX_IDLE); //最大空闲连接数, 默认8
            config.setMaxWaitMillis(MAX_WAIT); //获取连接时的最大等待时间(毫秒)
            config.setMinIdle(MIN_IDLE); //最小空闲连接数, 默认0
            config.setTestOnBorrow(true); //在获取连接时检查有效性, 默认false
            config.setTestOnReturn(true); //在返还连接时检查有效性, 默认false
            config.setTestWhileIdle(true);//在链接空闲时检查有效性, 默认false
            config.setTimeBetweenEvictionRunsMillis(30000); //逐出扫描的时间间隔(毫秒)
            config.setNumTestsPerEvictionRun(10); //每次逐出检查时最大逐出数目
            config.setMinEvictableIdleTimeMillis(60000); //逐出连接的最小空闲时间(毫秒)

            if (auth==null || "".equals(auth.trim())) {
                redisSentinelJedisPool = new JedisSentinelPool(clusterName, sentinels, config, auth);
            } else {
                redisSentinelJedisPool = new JedisSentinelPool(clusterName, sentinels, config);
            }
        }
    }

    // 获取redis连接
    private static Jedis getJedis() {
        Jedis resource = null;
        int count = 0;
        while (resource == null && count < 20) {
            try {
                resource = redisSentinelJedisPool.getResource();
            } catch (Exception e) {
                count++;
                if (resource != null) {
                    resource.close();
                    resource = null;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return resource;
    }

    // 从redis中获取用户信息
    public static String getUserInfo(String name) {
        String userInfo = null;
        Jedis resource = getJedis();
        try {
            userInfo = resource.get(name);
        } catch (Exception e) {
            LOG.error("从Redis连接池中获取连接异常!异常消息:", e);
        } finally {
            if (resource != null) {
                try {
                    resource.close();
                    resource = null;
                } catch (Exception e) {
                    LOG.warn("返还连接异常!异常消息:", e);
                }
            }
        }
        return userInfo;
    }
}
2.Redis 集群模式 操作工具类
package redis;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.*;

public class RedisClusterUtil {
    private static final Logger LOG = LoggerFactory.getLogger(RedisSentinelUtil.class);
    // 最大连接实例的最大数目(默认值8)
    private static int MAX_TOTAL = -1;
    // 最多有多少个状态为idle(空闲的)的jedis实例(默认值8)
    private static int MAX_IDLE = 300;
    // 连接的最大时间,单位毫秒
    private static int MAX_WAIT = 3 * 1000;
    private static int MIN_IDLE = 100;
    private static ShardedJedisPool shardedJedisPool = null ;
    //private static JedisSentinelPool redisSentinelJedisPool = null;

    // 获取Jedis线程池
    public static synchronized void getPool(String addr) {
        if (shardedJedisPool == null) {
            String[] hostAndPorts = addr.split(",");
            List<JedisShardInfo> shardInfos = new ArrayList<JedisShardInfo>();
            for (String string : hostAndPorts) {
                shardInfos.add(new JedisShardInfo(string.split(":")[0],string.split(":")[1]));
            }
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_TOTAL); //最大连接数, 默认8
            config.setMaxIdle(MAX_IDLE); //最大空闲连接数, 默认8
            config.setMaxWaitMillis(MAX_WAIT); //获取连接时的最大等待时间(毫秒)
            config.setMinIdle(MIN_IDLE); //最小空闲连接数, 默认0
            config.setTestOnBorrow(true); //在获取连接时检查有效性, 默认false
            config.setTestOnReturn(true); //在返还连接时检查有效性, 默认false
            config.setTestWhileIdle(true);//在链接空闲时检查有效性, 默认false
            config.setTimeBetweenEvictionRunsMillis(30000); //逐出扫描的时间间隔(毫秒)
            config.setNumTestsPerEvictionRun(10); //每次逐出检查时最大逐出数目
            config.setMinEvictableIdleTimeMillis(60000); //逐出连接的最小空闲时间(毫秒)

            shardedJedisPool = new ShardedJedisPool(config, shardInfos);
        }
    }

    // 获取redis连接
    private static ShardedJedis getJedis() {
        ShardedJedis resource = null;
        int count = 0;
        while (resource == null && count < 20) {
            try {
                resource = shardedJedisPool.getResource();
            } catch (Exception e) {
                count++;
                if (resource != null) {
                    resource.close();
                    resource = null;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return resource;
    }

    // 从redis中获取用户信息
    public static String getUserInfo(String name) {
        String userInfo = null;
        ShardedJedis resource = getJedis();
        try {
            userInfo = resource.get(name);
        } catch (Exception e) {
            LOG.error("从Redis连接池中获取连接异常!异常消息:", e);
        } finally {
            if (resource != null) {
                try {
                    resource.close();
                    resource = null;
                } catch (Exception e) {
                    LOG.warn("返还连接异常!异常消息:", e);
                }
            }
        }
        return userInfo;
    }
}
3.RedisDemo
package redis;

public class RedisDemo {
    public static void main(String[] args) {
        //哨兵模式
        String clusterName = "mymaster";
        String redisIP = "ml20.com:26379,ml21.com:26379,ml22.com:26379";
        String redisAuth = "";
        RedisSentinelUtil.getPool(clusterName, redisIP, redisAuth);
        String aaron = RedisSentinelUtil.getUserInfo("Aaron");
        System.out.println(aaron);
        //集群模式
        String redisIP2 = "ml11.com:6379,ml12.com:6379,ml13.com:6379";
        RedisClusterUtil.getPool(redisIP2);
        String aaron2 = RedisClusterUtil.getUserInfo("Aaron");
        System.out.println(aaron2);
    }
}

====================================================================

@羲凡——只为了更好的活着

若对博客中有任何问题,欢迎留言交流

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值