DownGradeService.java 2.92 KB
package com.yoho.search.common.downgrade;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yoho.search.common.downgrade.impl.AutoDownGradeByOverTime;
import com.yoho.search.service.base.SearchDynamicConfigService;

@Service
public class DownGradeService {

	private static final Logger logger = LoggerFactory.getLogger("DOWNGRADE");
	
	//private static final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

	@Autowired
	private DownGradeCacheService downGradeCacheService;
	@Autowired
	private SearchDynamicConfigService searchDynamicConfigService;

	private IDowngrade downgrade;

	private volatile DownGradeLevelEnum downGradeLevel;

	@PostConstruct
	void init() {
		// 降级方案:1分钟超时100次
		downgrade = new AutoDownGradeByOverTime(1, TimeUnit.MINUTES, 100);
		// 执行定时检查状态的机制
		//scheduledExecutorService.scheduleAtFixedRate(new AutoChangeDownGradeLevel(), 1, 1, TimeUnit.MINUTES);
		//判断默认的降级状态
		if(this.directDownGrade()){
			downGradeLevel = DownGradeStateMachine.getDirectDownGradeLevel();
		}else{
			downGradeLevel = DownGradeLevelEnum.DOWN_GRADE_LEVEL_OFF;// 初始默认是off,不走降级
		}
	}
	
	/**
	 * 是否直接走降级
	 * @return
	 */
	public boolean directDownGrade(){
		return searchDynamicConfigService.directDowngrade();
	}
	
	/**
	 * 试图执行降级操作
	 */
	public void tryDowngrade() {
		downgrade.tryDowngrade();
	}

	/**
	 * 从降级缓存中获取对象
	 * 
	 * @param redisKey
	 * @param clazz
	 * @return
	 */
	public <T> T cacheSafeGet(String redisKey, Class<T> clazz) {
		return downGradeLevel.cacheSafeGet(downGradeCacheService, redisKey, clazz);
	}

	/**
	 * 将对象存入降级缓存中
	 * 
	 * @param redisKey
	 * @param clazz
	 * @return
	 */
	public void cacheSafeAdd(String redisKey, Object result, int expireTimeInMinute) {
		downGradeCacheService.safeAdd(redisKey, result, expireTimeInMinute);
	}
	
	private class AutoChangeDownGradeLevel implements Runnable {
		@Override
		public void run() {
			try {
				//如果zk中直接开启了降级逻辑,则直接获取全降级level
				if(directDownGrade()){
					downGradeLevel = DownGradeStateMachine.getDirectDownGradeLevel();
					return;
				}
				// 如果超过次数,走降级通道
				if (downgrade.needDowngrade() || directDownGrade()) {
					downGradeLevel = DownGradeStateMachine.changeDownGradeLevel(downGradeLevel, true);
				} else {
					// 如果没有超过次数,走恢复通道
					downGradeLevel = DownGradeStateMachine.changeDownGradeLevel(downGradeLevel, false);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

}