项目中经常使用redis,我就把我写的一个获取redis实例记录下来
目录结构:
资源文件prop.properties内容,格式如下
redis服务器地址1:端口号1,redis服务器地址2:端口号2,redis服务器地址3:端口号3
pom.xml内容
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.czb</groupId> <artifactId>testRedis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.6.1</version> </dependency> </dependencies> </project>
获取redis实例代码RedisClientManager.java
package com.czb.redis; import java.io.InputStream; import java.util.HashSet; import java.util.Properties; import java.util.Set; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; public class RedisClientManager { private JedisCluster jedisCluster; public JedisCluster getJedisCluster() throws Exception { tryInitialize(); return jedisCluster; } private void tryInitialize() throws Exception { Properties prop = new Properties(); InputStream fis = RedisClientManager.class.getClassLoader().getResourceAsStream("prop.properties");// 属性文件流 prop.load(fis); final String[] lists = prop.getProperty("redis").split(","); Set<HostAndPort> set = new HashSet<HostAndPort>(); for (int i = 0; i < lists.length; i++) { final String[] redis = lists[i].split(":"); if (redis.length == 2) { set.add(new HostAndPort(redis[0],redis[1].matches("^[0-9]*$") ? Integer .parseInt(redis[1]) : 6397)); } } RedisConnector connector = new RedisConnector(set); jedisCluster = connector.getConnectedInstance(); } } class RedisConnector { private static Set<HostAndPort> set; public RedisConnector(Set<HostAndPort> set) { this.set = set; } private static class JedisHolder { private static JedisCluster jedisClusterInstance = new JedisCluster(set); } public JedisCluster getConnectedInstance() { return JedisHolder.jedisClusterInstance; } }
测试例子RedisServiceImpl.java
package com.czb.redis.service; import com.czb.redis.RedisClientManager; public class RedisServiceImpl extends RedisClientManager { public void addData() throws Exception{ this.getJedisCluster().set("name","zhangsan"); } public String getData(String name) throws Exception{ return this.getJedisCluster().get(name); } public static void main(String[] args) throws Exception { RedisServiceImpl redisServiceImpl = new RedisServiceImpl(); //redisServiceImpl.addData(); System.out.println(redisServiceImpl.getData("name")); } }
redis有5种数据结构存储,这里采用最简单的String类型,先存储在获取。单例的获取采用的是静态内部类方式,保证了线程安全。我觉得这种获取单例的方式挺好的。