Jedis 工具类

 

package com.pig4cloud.pigx.admin.utils;

import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.List;

public class RedisClient {

	private static Jedis jedis;//非切片额客户端连接
	private static JedisPool jedisPool;//非切片连接池
	private static ShardedJedis shardedJedis;//切片额客户端连接
	private static ShardedJedisPool shardedJedisPool;//切片连接池
	private static JedisPoolConfig config;


	static {
		initJedisPoolConfig();
		initialPool();
		initialShardedPool();
		shardedJedis = shardedJedisPool.getResource();
		jedis = jedisPool.getResource();
	}

	private static void initJedisPoolConfig(){
		// 池基本配置
		config = new JedisPoolConfig();
		config.setMaxTotal(20);
		config.setMaxIdle(5);
		config.setMaxWaitMillis(2000l);
		config.setTestOnBorrow(false);
	}


	/**
	 * 初始化非切片池
	 */
	private static void initialPool()
	{
		jedisPool = new JedisPool(config,"localhost",6379);
	}

	/**
	 * 初始化切片池
	 */
	private static void initialShardedPool()
	{
		// slave链接
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		JedisShardInfo  jedisShardInfo = new JedisShardInfo("localhost", 6379, "master");
		jedisShardInfo.setPassword("123456");
		shards.add(jedisShardInfo);
		// 构造池
		shardedJedisPool = new ShardedJedisPool(config, shards);
	}

	private static boolean lock(String lockKey){
		Long flag = shardedJedisPool.getResource().setnx(lockKey, "true");
		return flag==0?false:true;
	}

	private static boolean unlock(String lockKey){
		getShardedJedis().del(lockKey);
	}

	public static ShardedJedis getShardedJedis(){
		return shardedJedisPool.getResource();
	}


	public static ShardedJedisPool getJedisPool(){
		return shardedJedisPool;
	}
}

 

  

 

posted @ 2019-05-13 14:26  梦见舟  阅读(234)  评论(0编辑  收藏  举报