Redis3.0 工具类,单机,分片,集群,最全的

单机工具类:

package com.java.test.cache;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisManager extends CacheManager {

	private static JedisPool pool = null;
	private static final String HOST = "192.168.12.120"; // ip
	private static final int PORT = 6379; // 端口
	private static final String AUTH = "123456"; // 密码(原始默认是没有密码)
	private static int MAX_ACTIVE = 1024; // 最大连接数
	private static int MAX_IDLE = 200; // 设置最大空闲数
	private static int MAX_WAIT = 10000; // 最大连接时间
	private static int TIMEOUT = 10000; // 超时时间
	private static boolean BORROW = true; // 在borrow一个事例时是否提前进行validate操作

	static {
		GenericObjectPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(MAX_ACTIVE);
		config.setMaxIdle(MAX_IDLE);
		config.setMaxWaitMillis(MAX_WAIT);
		config.setTestOnBorrow(BORROW);

		pool = new JedisPool(config, HOST, PORT,TIMEOUT,AUTH);
//		pool = new JedisPool(config, HOST, PORT);
	}

	public static synchronized Jedis getJedis() {
		try {
			if (pool != null) {
				return pool.getResource();
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	//
	public static void disableTime(String key, int seconds) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			if (jedis != null) {
				jedis.expire(key, seconds);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getColse(jedis);
		}
	}

	public static boolean addObject(String key, Object obj) {
		Jedis jedis = null;
		String value = com.alibaba.fastjson.JSONObject.toJSONString(obj);
		try {
			jedis = getJedis();
			String code = jedis.set(key, value);
			if (code.equals("ok")) {
				return true;
			}
		} catch (Exception e) {
			return false;
		} finally {
			getColse(jedis);
		}
		return false;
	}

	public static boolean addValue(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			String code = jedis.set(key, value);
			if (code.equals("ok")) {
				return true;
			}
		} catch (Exception e) {
			return false;
		} finally {
			getColse(jedis);
		}
		return false;
	}

	public static boolean delKey(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			Long code = jedis.del(key);
			if (code > 1) {
				return true;
			}
		} catch (Exception e) {
			return false;
		} finally {
			getColse(jedis);
		}
		return false;
	}

	public static void getColse(Jedis jedis) {
		try {
			if (jedis != null) {
				jedis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Object get(String key) {
		return getJedis().get(key);
	}

	@Override
	public String getName() {
		return CacheEnum.REDIS.getValue();
	}

	public static void main(String[] args) {
//		Jedis jedis = new Jedis("192.168.12.120", 6379);
//		System.out.println("connetion ok:" + jedis.ping());
//		// System.out.println(jedis.asking());
//		jedis.set("runkey", "www.run.com");
//		System.out.println(jedis.get("runkey"));
//		System.out.println("---------------------");
//		//
//		jedis.lpush("site", "google");
//		jedis.lpush("site", "baidu");
//		jedis.lpush("site", "ali");
//		List<String> lrange = jedis.lrange("site", 0, 2);
//		for (int i = 0; i < lrange.size(); i++) {
//			System.out.println(lrange.get(i));
//		}
//		System.out.println("---------------------");
//		//
//		Set<String> keys = jedis.keys("*");
//		Iterator<String> iterator = keys.iterator();
//		while (iterator.hasNext()) {
//			System.out.println(iterator.next());
//		}
		System.out.println(RedisManager.get("runkey"));
//		System.out.println(RedisManager.addValue("mykey", "www.run.com"));
		
		for (int i = 0; i < 1000; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(RedisManager.get("mykey"));
				}
			}).start();
		}
		for (int i = 0; i < 1000; i++) {
			
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					RedisManager.addValue("mykey",Math.abs( Math.random()*100)+"");
				}
			}).start();
		}
		
	}
}

分片工具类:

package com.java.test.cache;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.Client;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisShardedManager extends CacheManager {

	private static ShardedJedisPool pool = null;

	private static final String AUTH = ""; // 密码(原始默认是没有密码)
	private static int MAX_ACTIVE = 1024; // 最大连接数
	private static int MAX_IDLE = 200; // 设置最大空闲数
	private static int MAX_WAIT = 10000; // 最大连接时间
	private static int TIMEOUT = 10000; // 超时时间
	private static boolean BORROW = true; // 在borrow一个事例时是否提前进行validate操作
	static List<JedisShardInfo> shards;
	static {
		GenericObjectPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(MAX_ACTIVE);
		config.setMaxIdle(MAX_IDLE);
		config.setMaxWaitMillis(MAX_WAIT);
		config.setTestOnBorrow(BORROW);
		JedisShardInfo shardInfo1 = new JedisShardInfo("192.168.12.121", 6379);
		JedisShardInfo shardInfo2 = new JedisShardInfo("192.168.12.120", 6379);
		shards = Arrays.asList(shardInfo1, shardInfo2);
		pool = new ShardedJedisPool(config, shards);
	}

	public static synchronized ShardedJedis getJedis() {
		if (pool == null) {
			return null;
		} else {
			return pool.getResource();
		}
	}

	@Override
	public String getName() {
		return "ShardedJedis";
	}

	public static void main(String[] args) {
		ShardedJedis jedis = getJedis();
		jedis.set("cnblog", "cnblog");
		jedis.set("redis", "redis");
		jedis.set("test", "test");
		jedis.set("123456", "1234567");
		Client client1 = jedis.getShard("cnblog").getClient();
		Client client2 = jedis.getShard("redis").getClient();
		Client client3 = jedis.getShard("test").getClient();
		Client client4 = jedis.getShard("123456").getClient();

		 打印key在哪个server中
		System.out.println("cnblog in server:" + client1.getHost() + " and port is:" + client1.getPort());
		System.out.println("redis  in server:" + client2.getHost() + " and port is:" + client2.getPort());
		System.out.println("test   in server:" + client3.getHost() + " and port is:" + client3.getPort());
		System.out.println("123456 in server:" + client4.getHost() + " and port is:" + client4.getPort());
	}
}

集群工具类:

package com.java.test.cache;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

public class RedisClusterManager extends CacheManager {

	
	private static int MAX_ACTIVE = 1024; // 最大连接数
	private static int MAX_IDLE = 200; // 设置最大空闲数
	private static int MAX_WAIT = 10000; // 最大连接时间
	private static boolean BORROW = true; // 在borrow一个事例时是否提前进行validate操作
	private RedisClusterManager() {}
	private static class JedisClusterHandler{
		private static JedisCluster jedisCluster = null;
	}
	static {
		GenericObjectPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(MAX_ACTIVE);
		config.setMaxIdle(MAX_IDLE);
		config.setMaxWaitMillis(MAX_WAIT);
		config.setTestOnBorrow(BORROW);
		Set<HostAndPort> nodes = new HashSet<>();
		HostAndPort node1 = new HostAndPort("192.168.12.121", 3301);
		HostAndPort node2 = new HostAndPort("192.168.12.121", 3302);
		HostAndPort node3 = new HostAndPort("192.168.12.121", 3303);
		nodes.add(node1);
		nodes.add(node2);
		nodes.add(node3);
		JedisClusterHandler.jedisCluster = new JedisCluster(nodes, config);
	}

	@Override
	public String getName() {
		return "rediscluster";
	}

	public static JedisCluster getJedisCluster() {
		return JedisClusterHandler.jedisCluster;
	}
	/**
	 * 设置String数据类型
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public String set(String key, String value) {
		return getJedisCluster().set(key, value);
	}

	/**
	 * 获取String数据类型
	 * 
	 * @param key
	 * @return
	 */
	
	public String get(String key) {
		return getJedisCluster().get(key);
	}

	/**
	 * 设置hash数据类型
	 * 
	 * @param key
	 * @param item
	 * @param value
	 * @return
	 */
	
	public Long hset(String key, String item, String value) {
		return getJedisCluster().hset(key, item, value);
	}

	/**
	 * 获取hash数据类型
	 * 
	 * @param key
	 * @param item
	 * @return
	 */
	
	public String hget(String key, String item) {
		return getJedisCluster().hget(key, item);
	}

	/**
	 * 删除hash数据
	 * 
	 * @param key
	 * @param item
	 * @return
	 */
	
	public Long incr(String key) {
		return getJedisCluster().incr(key);
	}

	/**
	 * 加一操作
	 * 
	 * @param key
	 * @return
	 */
	
	public Long decr(String key) {
		return getJedisCluster().decr(key);
	}

	/**
	 * 减一操作
	 * 
	 * @param key
	 * @return
	 */
	
	public Long expire(String key, int second) {
		return getJedisCluster().expire(key, second);
	}

	/**
	 * 设置key的过期时间
	 * 
	 * @param key
	 * @param second
	 * @return
	 */
	
	public Long ttl(String key) {
		return getJedisCluster().ttl(key);
	}

	/**
	 * 判断key是否过期
	 * 
	 * @param key
	 * @return
	 */
	
	public Long hdel(String key, String item) {
		return getJedisCluster().hdel(key, item);
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值