关于单例模式在实际开发中的问题

2020-01-17  本文已影响0人  alvan_wyal

1:背景:适配Memcached

@Service(value ="cache")

public class CacheSystem {

private static StringHOST ="";

private static StringPORT ="";

private static StringUSERNAME ="";

private static StringPASSWORD ="";

private static MemcachedClientcache =null;

private static CacheSystem  cacheSystem =null;

public static MemcachedClient getInstance() {

if (cacheSystem ==null) {

synchronized (CacheSystem.class) {

if (cacheSystem ==null) {

try {

HOST = MemcacheConfiguration.ip;

PORT = MemcacheConfiguration.port +"";

if(MemcacheConfiguration.username!=null && MemcacheConfiguration.password!=null ){

USERNAME = MemcacheConfiguration.username;

PASSWORD = MemcacheConfiguration.password;

}

if (HOST.isEmpty() ||PORT.isEmpty()) {

logger.error("Wrong OCS Config!Can't start the OCS cache system!");

}else {

if (USERNAME.isEmpty() ||PASSWORD.isEmpty()) {

//无用户密码方式

                            logger.info("Create the OCS client with no account and pwd......");

cache =new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses(HOST +":" +PORT));

}else {

//有用户密码方式

                            logger.info("Create the OCS client with account and pwd......");

AuthDescriptor ad =new AuthDescriptor(new String[]{"PLAIN"},new PlainCallbackHandler(USERNAME,PASSWORD));

cache =new MemcachedClient(new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY)

.setAuthDescriptor(ad)

.build(),

AddrUtil.getAddresses(HOST +":" +PORT));

}

logger.info("OCS client is running.");

}

}catch (Exception e) {

logger.error("Start OCS client unsuccessful!Please make sure that the Config is all right,then restart it again.");

logger.error("[OCS]", e);

}

}

}

}

return cache;

}

2:在下面方法中调用时创建对象

例如:

/**

* 使用方式和get相同,需配合put方法使用

*

* @param

* @param key

* @param typeToken

* @return

*/

public static T getList(String key, TypeToken> typeToken) {

try {

return gson.fromJson((String)getInstance().get(key), typeToken.getType());

}catch (Exception e) {

logger.error("[OCS get error]", e);

return null;

}

}

}

3:使用单例模式中的懒汉模式解决在代码中静态代码块儿优先于配置文件加载;

注:在单例模式中两层判空;防止线程池中有活跃的线程,二次获取;

上一篇 下一篇

猜你喜欢

热点阅读