Redis默认有16个库,默认连接的是 index=0
的那一个。这16个库互相之间是独立的。
这里1为db index:
spring.redis.shard.1.host2=http://ip:6379/1 spring.redis.shard.1.password = 123456
spring.redis.pool.maxIdle = 300 spring.redis.pool.maxActive=300 spring.redis.pool.maxTotal = 300 #连接数
注入ShardedJedisPool:
1 @Autowired 2 private Environment env; 3 4 @Bean 5 @ConfigurationProperties(prefix = "spring.redis.pool") 6 public JedisPoolConfig getJedisPoolConfig() { 7 return new JedisPoolConfig(); 8 } 9 10 @Bean11 public ShardedJedisPool getJedisPool() {12 try {13 ListshardList = new ArrayList<>();14 // 读取host15 String host = env.getProperty("spring.redis.shard.1.host2");16 JedisShardInfo info = new JedisShardInfo(host);17 // 读取password18 String password = env.getProperty("spring.redis.shard.1.password");19 if (!StringUtils.isEmpty(password)) {20 info.setPassword(password);21 }22 shardList.add(info);23 if (shardList.isEmpty()) {24 // 无法加载redis25 throw new IOException();26 }27 return new ShardedJedisPool(getJedisPoolConfig(), shardList);28 } catch (Exception e) {29 logger.error(LogUtils.getExceptionInfo(e));30 throw new RedisConfigException("无法加载资源文件!");31 }32 }
redis保存key,获取key,删除key,判断key:
1 publicvoid setObjectJosn(String key, T obj, int time) { #保存对象(json) 2 ShardedJedis jedis = null; 3 try { 4 jedis = shardedJedisPool.getResource(); 5 jedis.set(key, JSON.toJSONString(obj)); 6 if (time > 0) { 7 jedis.expire(key, time); 8 } 9 logger.info(String.format("redis setObject info:[key:%s,value:%s,outTime:%d]", key, obj.toString(), time));10 } catch (Exception e) {11 logger.error(LogUtils.getExceptionInfo(e));12 } finally {13 jedis.close();14 }15 }
1 public String getObjectJosn(String key) { #获取对象(json) 2 String s = null; 3 ShardedJedis jedis = null; 4 try { 5 jedis = shardedJedisPool.getResource(); 6 s = jedis.get(key); 7 logger.info(String.format("redis getObject info:[key:%s,value:%s]", key, s == null ? "null" : s.toString())); 8 } catch (Exception e) { 9 logger.error(LogUtils.getExceptionInfo(e));10 } finally {11 jedis.close();12 }13 return s;14 }
1 public Long delete(String key) { #根据key删除对象 2 Long temp = null; 3 ShardedJedis jedis = null; 4 try { 5 jedis = shardedJedisPool.getResource(); 6 // temp = jedis.del(key.getBytes()); 7 temp = jedis.del(key); 8 logger.info(String.format("redis deleteDate info:[key:%s]", key)); 9 } catch (Exception e) {10 logger.error(LogUtils.getExceptionInfo(e));11 } finally {12 jedis.close();13 }14 return temp;15 }
1 public boolean isExist(String key) { #判断是否存在 2 boolean flag = false; 3 ShardedJedis jedis = null; 4 try { 5 jedis = shardedJedisPool.getResource(); 6 // flag = jedis.exists(key.getBytes()); 7 flag = jedis.exists(key); 8 9 logger.info(String.format("redis isExist info:[key:%s]", key));10 } catch (Exception e) {11 logger.error(LogUtils.getExceptionInfo(e));12 } finally {13 jedis.close();14 }15 return flag;16 }
测试:
1 if (redis.isExist("112e35b563520aed051d7cbf8f477338")) { 2 System.out.println("xxxxx:" + redis.getObjectJosn("test")); 3 JSONObject json = JSONObject.parseObject(redis.getObjectJosn("test")); 4 System.out.println("asdasdasd===:"+json.get("name")); 5 } else { 6 Mapmap = new HashMap<>(); 7 map.put("name", "yao"); 8 map.put("age", "20"); 9 String token= DigestUtils.md2Hex(System.currentTimeMillis()+"test");10 redis.setObjectJosn(token,null, map, 86400); // 保存token到redis11 }
相关源码部分:
JedisPoolConfig:
1 public class JedisPoolConfig extends GenericObjectPoolConfig { 2 public JedisPoolConfig() { 3 this.setTestWhileIdle(true); 4 this.setMinEvictableIdleTimeMillis(60000L); 5 this.setTimeBetweenEvictionRunsMillis(30000L); 6 this.setNumTestsPerEvictionRun(-1); 7 } 8 9 public class GenericObjectPoolConfig extends BaseObjectPoolConfig {10 public static final int DEFAULT_MAX_TOTAL = 8;11 public static final int DEFAULT_MAX_IDLE = 8;12 public static final int DEFAULT_MIN_IDLE = 0;13 private int maxTotal = 8; #我们修改的部分14 private int maxIdle = 8; #我们修改的部分15 private int minIdle = 0;16 17 public GenericObjectPoolConfig() {18 }19 }
JedisShardInfo:
public class JedisShardInfo extends ShardInfo{ private int connectionTimeout; private int soTimeout; private String host; private int port; private String password; private String name; private int db; private boolean ssl; private SSLSocketFactory sslSocketFactory; private SSLParameters sslParameters; private HostnameVerifier hostnameVerifier; public JedisShardInfo(String host) { #用的这个构造 super(1); this.password = null; this.name = null; this.db = 0; URI uri = URI.create(host); if (JedisURIHelper.isValid(uri)) { this.host = uri.getHost(); this.port = uri.getPort(); this.password = JedisURIHelper.getPassword(uri); this.db = JedisURIHelper.getDBIndex(uri); this.ssl = uri.getScheme().equals("rediss"); } else { this.host = host; this.port = 6379; } } public JedisShardInfo(String host, int port, int timeout, String name) { this(host, port, timeout, timeout, 1); this.name = name; } public JedisShardInfo(String host, int port, int timeout, String name, boolean ssl) { this(host, port, timeout, timeout, 1); this.name = name; this.ssl = ssl; } ........可以看看其他的选择}
ShardedJedisPool:
public class ShardedJedisPool extends Pool{ public ShardedJedisPool(GenericObjectPoolConfig poolConfig, List shards) { #参数:1.池配置,2.连接信息 this(poolConfig, shards, Hashing.MURMUR_HASH); } public ShardedJedisPool(GenericObjectPoolConfig poolConfig, List shards, Hashing algo) { this(poolConfig, shards, algo, (Pattern)null); } .....}