本文主要是介绍Java Java实现的多例模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
参考文章
设计模式之多例模式
https://www.cnblogs.com/scetopcsa/p/4295111.html
Java 多例模式实际就是单例模式的一个扩展,下面给出一个多例模式的实现
需要引入的Java包
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version><type>jar</type><scope>compile</scope>
</dependency>
RedisClusterMulti.java
package com.yaobaling.td.blacklist.redis;import redis.clients.jedis.JedisCluster;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;/*** Created by szh on 2018/10/29.** @author szh*/
public class RedisClusterMulti implements Serializable {private static final Integer MAX_JEDIS_CLUSTER_NUM = 20;private static List<RedisCluster> redisClusterList = new ArrayList<>();private static final Random random = new Random();private RedisClusterMulti() {}public static void init(Properties conf) throws Exception {for (int i = 0; i < MAX_JEDIS_CLUSTER_NUM; i++) {redisClusterList.add(new RedisCluster(conf));}}public static JedisCluster getJedisCluster() {int index = random.nextInt(MAX_JEDIS_CLUSTER_NUM);return redisClusterList.get(index).getClusterConn();}
}
RedisCluster.java
package com.yaobaling.td.blacklist.redis;import com.yaobaling.td.blacklist.config.ConfigCenter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;import java.io.Serializable;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;/*** Created by szh on 2018/10/9.** @author szh* @date 2018-10-09*/
public class RedisCluster implements Serializable{private JedisCluster jedisCluster = null;public RedisCluster(Properties config) throws Exception {String clusterAddr = null;if (StringUtils.isNotBlank(config.getProperty("redis.cluster.addr"))) {clusterAddr = config.getProperty("redis.cluster.addr");}Set<HostAndPort> hostAndPortSet = new HashSet<>();String[] addrList = clusterAddr.split(",");for (String tmpAddr : addrList) {String[] tmpHostAndPortArr = tmpAddr.split(":");HostAndPort tmphostAndPort = new HostAndPort(tmpHostAndPortArr[0], Integer.valueOf(tmpHostAndPortArr[1]));hostAndPortSet.add(tmphostAndPort);}//进行设置,防止以下异常: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the poolGenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();genericObjectPoolConfig.setMinIdle(10);genericObjectPoolConfig.setMaxIdle(100);jedisCluster = new JedisCluster(hostAndPortSet,genericObjectPoolConfig);}public JedisCluster getClusterConn() {return jedisCluster;}}
这篇关于Java Java实现的多例模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!