DownGradeService.java
2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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);
}
}
}
}