java zk监听异步_zookeeper实现项目初始化缓存以及同步监听

packagecom.blog.cas.common.dic;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.blog.cas.common.constants.Constants;importcom.blog.cas.common.utils.BeanFactoryUtils;importcom.blog.cas.common.utils.Detect;importcom.blog.cas.common.utils.json.JsonUtils;importcom.blog.cas.common.zk.CacheDataSynServerHandle;importcom.blog.cas.common.zk.RetryRecord;importcom.blog.cas.common.zk.ZkClientUtils;importcom.blog.cas.repository.entity.BlogDictionary;importcom.blog.cas.service.IDictionaryService;importorg.apache.log4j.Logger;importjava.util.Date;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantReadWriteLock;/*** 本地缓存操作类

*@authorhzk

* @date 2018/11/14*/

public classLoadData {private static final Logger logger = Logger.getLogger(LoadData.class);/*** itemKey value*/

private static Map dicInfoMap = new HashMap<>();/*** Id value*/

private static Map dicInfoIdMap = new HashMap<>();private static ReentrantReadWriteLock rwl = newReentrantReadWriteLock();private static Lock r =rwl.readLock();private static Lock w =rwl.writeLock();/*------------------------------------------ mysql select-------------------------------------------*/

/*** 通过itemKey从数据库中查询数据

*@paramkey

*@return{@linkBlogDictionary}*/

private staticBlogDictionary getDicByItemKeyWithIfc(String key){

IDictionaryService blogDictionaryService= BeanFactoryUtils.getInstance("dictionaryService");returnblogDictionaryService.selectByItemKey(key);

}/*** 通过id从数据库中查询数据

*@paramid

*@return{@linkBlogDictionary}*/

private staticBlogDictionary getDicByIdWithIfc(Integer id){

IDictionaryService blogDictionaryService= BeanFactoryUtils.getInstance("dictionaryService");returnblogDictionaryService.selectByPrimaryKey(id);

}/*------------------------------------------by itemKey-------------------------------------------*/

/*** 通过itemKey查询字典

*@paramkey

*@return{@linkBlogDictionary}*/

public staticBlogDictionary getDicByItemKey(String key) {

r.lock();try{

BlogDictionary dictionary=dicInfoMap.get(key);if (dictionary != null) {returndictionary;

}

retryBuildLocalCache(dicInfoMap);

BlogDictionary dicByItemKeyWithIfc=getDicByItemKeyWithIfc(key);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc;

}

logger.warn("======Not Found Dic key:" +key);return null;

}finally{

r.unlock();

}

}/*** 通过itemKey查询字典value

*@paramkey 字典key

*@paramcheck 是否验证启用

*@return

*/

public static String getDicValueByItemKey(String key,booleancheck) {

r.lock();try{

BlogDictionary dictionary=dicInfoMap.get(key);if (dictionary != null) {if(check){if(Detect.equal(LoadData.getDicIdByItemKey(Constants.AbstractPublicStatus.ENABLE),dictionary.getFrState())){returndictionary.getItemValue();

}else{return null;

}

}else{returndictionary.getItemValue();

}

}

retryBuildLocalCache(dicInfoMap);

BlogDictionary dicByItemKeyWithIfc=getDicByItemKeyWithIfc(key);if(null !=dicByItemKeyWithIfc){if(check){if(Detect.equal(LoadData.getDicIdByItemKey(Constants.AbstractPublicStatus.ENABLE),dicByItemKeyWithIfc.getFrState())){returndicByItemKeyWithIfc.getItemValue();

}else{return null;

}

}else{returndicByItemKeyWithIfc.getItemValue();

}

}

logger.warn("======Not Found Dic key:" +key);return null;

}finally{

r.unlock();

}

}/*** 通过itemKey查询字典value

*@paramkey 字典key

*@paramdefaultValue 不存在时设置默认值

*@return

*/

public staticString getDicValueByItemKey(String key,String defaultValue){

r.lock();try{

BlogDictionary dictionary=dicInfoMap.get(key);if (dictionary != null) {returndictionary.getItemValue();

}

retryBuildLocalCache(dicInfoMap);

BlogDictionary dicByItemKeyWithIfc=getDicByItemKeyWithIfc(key);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getItemValue();

}

logger.warn("======Not Found Dic key:" +key);returndefaultValue;

}finally{

r.unlock();

}

}/*** 通过itemKey查询字典ID

*@paramkey 字典key

*@return

*/

public static intgetDicIdByItemKey(String key) {

r.lock();try{

BlogDictionary dictionary=dicInfoMap.get(key);if (dictionary != null) {returnDetect.asPrimitiveInt(dictionary.getId());

}

retryBuildLocalCache(dicInfoMap);

BlogDictionary dicByItemKeyWithIfc=getDicByItemKeyWithIfc(key);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getId();

}

logger.warn("======Not Found Dic key:" +key);return 0;

}finally{

r.unlock();

}

}/*** 通过itemKey查询字典中文名称

*@paramkey 字典key

*@return

*/

public staticString getDicNameByItemKey(String key) {

r.lock();try{

BlogDictionary dictionary=dicInfoMap.get(key);if (dictionary != null) {returnDetect.asString(dictionary.getItemNamecn());

}

retryBuildLocalCache(dicInfoMap);

BlogDictionary dicByItemKeyWithIfc=getDicByItemKeyWithIfc(key);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getItemNamecn();

}

logger.warn("======Not Found Dic key:" +key);return null;

}finally{

r.unlock();

}

}/*------------------------------------------by id-------------------------------------------*/

/*** 通过ID查询字典

*@paramid 字典ID

*@return{@linkBlogDictionary}*/

public staticBlogDictionary getDicById(Integer id) {

r.lock();try{

BlogDictionary dictionary=dicInfoIdMap.get(id);if (dictionary != null) {returndictionary;

}else{

retryBuildLocalCache(dicInfoIdMap);

BlogDictionary dicByItemKeyWithIfc=getDicByIdWithIfc(id);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc;

}

logger.warn("======Not Found Dic id:" +id);return null;

}

}finally{

r.unlock();

}

}/*** 通过id查询字典value

*@paramid 字典ID

*@return

*/

public staticString getDicValueById(Integer id) {

r.lock();try{

BlogDictionary dictionary=dicInfoIdMap.get(id);if (dictionary != null) {returndictionary.getItemValue();

}else{

retryBuildLocalCache(dicInfoIdMap);

BlogDictionary dicByItemKeyWithIfc=getDicByIdWithIfc(id);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getItemValue();

}

logger.warn("======Not Found Dic id:" +id);return null;

}

}finally{

r.unlock();

}

}/*** 通过ID查询字典itemKey

*@paramid 字典ID

*@return

*/

public staticString getDicItemKeyById(Integer id) {

r.lock();try{

BlogDictionary dictionary=dicInfoIdMap.get(id);if (dictionary != null) {returnDetect.asString(dictionary.getItemKey());

}else{

retryBuildLocalCache(dicInfoIdMap);

BlogDictionary dicByItemKeyWithIfc=getDicByIdWithIfc(id);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getItemKey();

}

logger.warn("======Not Found Dic id:" +id);return null;

}

}finally{

r.unlock();

}

}/*** 通过ID查询字典parentId

*@paramid 字典ID

*@return

*/

public staticInteger getDicParentIdById(Integer id) {

r.lock();try{

BlogDictionary dictionary=dicInfoIdMap.get(id);if (dictionary != null) {returndictionary.getParentId();

}else{

retryBuildLocalCache(dicInfoIdMap);

BlogDictionary dicByItemKeyWithIfc=getDicByIdWithIfc(id);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getParentId();

}

logger.warn("======Not Found Dic id:" +id);return null;

}

}finally{

r.unlock();

}

}/*** 通过ID查询字典中文名称

*@paramid 字典ID

*@return

*/

public staticString getDicNameById(Integer id) {

r.lock();try{

BlogDictionary dictionary=dicInfoIdMap.get(id);if (dictionary != null) {returnDetect.asString(dictionary.getItemNamecn());

}else{

retryBuildLocalCache(dicInfoIdMap);

BlogDictionary dicByItemKeyWithIfc=getDicByIdWithIfc(id);if(null !=dicByItemKeyWithIfc){returndicByItemKeyWithIfc.getItemNamecn();

}

logger.warn("======Not Found Dic id:" +id);return null;

}

}finally{

r.unlock();

}

}/*------------------------------------------init data-------------------------------------------*/

/*** 初始化内存数据

* 字典/合作方*/

public static void buildLocalCache(ListdataDic){

w.lock();try{//初始化数据字典

logger.warn("-------------------init dictionary start...---------------------");for(BlogDictionary blogDictionary : dataDic) {

dicInfoMap.put(Detect.trim(blogDictionary.getItemKey()), blogDictionary);

dicInfoIdMap.put(blogDictionary.getId(), blogDictionary);

}

logger.warn("-------------------init dictionary complete---------------------");

}catch(Exception e){

e.printStackTrace();

logger.warn("-------------------init LoadData error---------------------"+e.getMessage());

}finally{

w.unlock();

}

}/*** 重试机制

* 若多次发现本地缓存为空 则重新加载本地数据*/

private static void retryBuildLocalCache(Map,BlogDictionary>dataDic){//内存中数据为null时 记录获取次数 到达一定次数尝试重试加载缓存

if(!Detect.notEmpty(dataDic)){

logger.warn("------ local cache dic is null -------");

ZkClientUtils zkClientUtils= newZkClientUtils();

Date currentDate= newDate(System.currentTimeMillis());try{if(!zkClientUtils.isExists(Constants.AbstractZkNodePath.ZK_RETRY_RECORD_PATH)){

logger.info("------ init retry record start... -------");

RetryRecord retryRecord= new RetryRecord(Detect.asString(currentDate.getTime()),0);

String data=JsonUtils.object2json(retryRecord);

zkClientUtils.create(Constants.AbstractZkNodePath.ZK_RETRY_RECORD_PATH, data);

logger.info("------ init retry record success -------");

}

String znodeData=zkClientUtils.getZnodeData(Constants.AbstractZkNodePath.ZK_RETRY_RECORD_PATH);

RetryRecord retryRecord= JSONObject.toJavaObject(JSON.parseObject(znodeData), RetryRecord.class);if(null !=retryRecord){

Integer retryCount=retryRecord.getRetryCount();if(null !=retryCount){if(retryCount % Constants.AbstractZkNodePath.ZK_RETRY_COUNT_REGEX == 1){//尝试重新加载本地缓存

newCacheDataSynServerHandle().reloadLocal();

}

retryRecord.setLastRecordTime(Detect.asString(currentDate.getTime()));

retryRecord.setRetryCount(retryCount+1);

String data=JsonUtils.object2json(retryRecord);

zkClientUtils.set(Constants.AbstractZkNodePath.ZK_RETRY_RECORD_PATH, data);

}

}

}catch(Exception e) {

e.printStackTrace();

logger.error("------ retry build local cache fail msg:"+e.getMessage());

}finally{

zkClientUtils.close();

}

}

}/*** 刷新zk字典节点缓存

*@return

*/

public static intrenovateZkDicCache(){

ZkClientUtils zkClientUtils= newZkClientUtils();int success = 1;

w.lock();try{

List blogDictionary =CacheDataSynServerHandle.getDicData();

String data=JsonUtils.list2json(blogDictionary);if(!zkClientUtils.isExists(Constants.AbstractZkNodePath.ZK_DICTIONRAY_PATH)){

zkClientUtils.create(Constants.AbstractZkNodePath.ZK_DICTIONRAY_PATH, data);

logger.info("------renovateZKData success!");

}else{

zkClientUtils.set(Constants.AbstractZkNodePath.ZK_DICTIONRAY_PATH, data);

logger.info("------renovateZKData success!");

}

}catch(Exception e) {

e.printStackTrace();

success= 0;

logger.error("------renovateZKData fail msg:"+e.getMessage());

}finally{

zkClientUtils.close();

w.unlock();

}returnsuccess;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值