/
AbstractServiceRegistry.java
316 lines (265 loc) · 11.4 KB
/
AbstractServiceRegistry.java
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.serviceregistry.registry;
import static org.apache.servicecomb.foundation.common.base.ServiceCombConstants.CONFIG_DEFAULT_REGISTER_BY;
import static org.apache.servicecomb.foundation.common.base.ServiceCombConstants.CONFIG_FRAMEWORK_DEFAULT_NAME;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import org.apache.servicecomb.foundation.common.concurrency.SuppressedRunnableWrapper;
import org.apache.servicecomb.registry.DiscoveryManager;
import org.apache.servicecomb.registry.api.event.MicroserviceInstanceChangedEvent;
import org.apache.servicecomb.registry.api.event.task.RecoveryEvent;
import org.apache.servicecomb.registry.api.event.task.SafeModeChangeEvent;
import org.apache.servicecomb.registry.api.event.task.ShutdownEvent;
import org.apache.servicecomb.registry.api.registry.BasePath;
import org.apache.servicecomb.registry.api.registry.Framework;
import org.apache.servicecomb.registry.api.registry.FrameworkVersions;
import org.apache.servicecomb.registry.api.registry.Microservice;
import org.apache.servicecomb.registry.api.registry.MicroserviceFactory;
import org.apache.servicecomb.registry.api.registry.MicroserviceInstance;
import org.apache.servicecomb.registry.api.registry.MicroserviceInstances;
import org.apache.servicecomb.registry.definition.MicroserviceDefinition;
import org.apache.servicecomb.serviceregistry.RegistryUtils;
import org.apache.servicecomb.serviceregistry.ServiceRegistry;
import org.apache.servicecomb.serviceregistry.api.Const;
import org.apache.servicecomb.serviceregistry.client.ServiceRegistryClient;
import org.apache.servicecomb.serviceregistry.config.ServiceRegistryConfig;
import org.apache.servicecomb.serviceregistry.registry.cache.MicroserviceCache;
import org.apache.servicecomb.serviceregistry.registry.cache.MicroserviceCacheKey;
import org.apache.servicecomb.serviceregistry.registry.cache.MicroserviceCacheRefreshedEvent;
import org.apache.servicecomb.serviceregistry.registry.cache.RefreshableServiceRegistryCache;
import org.apache.servicecomb.serviceregistry.registry.cache.ServiceRegistryCache;
import org.apache.servicecomb.serviceregistry.task.MicroserviceServiceCenterTask;
import org.apache.servicecomb.serviceregistry.task.ServiceCenterTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.MoreExecutors;
public abstract class AbstractServiceRegistry implements ServiceRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServiceRegistry.class);
private MicroserviceFactory microserviceFactory = new MicroserviceFactory();
protected EventBus eventBus;
protected MicroserviceDefinition microserviceDefinition;
protected Microservice microservice;
protected ServiceRegistryClient srClient;
protected ServiceRegistryConfig serviceRegistryConfig;
protected ServiceCenterTask serviceCenterTask;
protected ExecutorService executorService = MoreExecutors.newDirectExecutorService();
private String name;
RefreshableServiceRegistryCache serviceRegistryCache;
public AbstractServiceRegistry(EventBus eventBus, ServiceRegistryConfig serviceRegistryConfig,
MicroserviceDefinition microserviceDefinition) {
setName(serviceRegistryConfig.getRegistryName());
this.eventBus = eventBus;
this.serviceRegistryConfig = serviceRegistryConfig;
this.microserviceDefinition = microserviceDefinition;
this.microservice = microserviceFactory.create(microserviceDefinition);
}
@Override
public void init() {
if (srClient == null) {
srClient = createServiceRegistryClient();
eventBus.register(srClient);
}
createServiceCenterTask();
eventBus.register(this);
initCache();
}
private void initCache() {
serviceRegistryCache = new RefreshableServiceRegistryCache(microservice, srClient);
serviceRegistryCache.setCacheRefreshedWatcher(
caches -> eventBus.post(new MicroserviceCacheRefreshedEvent(caches)));
}
@Override
public EventBus getEventBus() {
return eventBus;
}
@Override
public Set<String> getCombinedMicroserviceNames() {
return microserviceDefinition.getCombinedFrom();
}
@Override
public ServiceRegistryClient getServiceRegistryClient() {
return srClient;
}
public void setServiceRegistryClient(ServiceRegistryClient serviceRegistryClient) {
this.srClient = serviceRegistryClient;
}
@Override
public String getAppId() {
return microservice.getAppId();
}
protected abstract ServiceRegistryClient createServiceRegistryClient();
@Override
public void run() {
loadStaticConfiguration();
loadFrameworkVersions();
// try register
// if failed, then retry in thread
serviceCenterTask.init();
}
private void loadFrameworkVersions() {
Framework framework = new Framework();
framework.setName(CONFIG_FRAMEWORK_DEFAULT_NAME);
framework.setVersion(FrameworkVersions.allVersions());
microservice.setFramework(framework);
microservice.setRegisterBy(CONFIG_DEFAULT_REGISTER_BY);
}
private void loadStaticConfiguration() {
// TODO 如果yaml定义了paths规则属性,替换默认值,现需要DynamicPropertyFactory支持数组获取
List<BasePath> paths = microservice.getPaths();
for (BasePath path : paths) {
if (path.getProperty() == null) {
path.setProperty(new HashMap<>());
}
path.getProperty().put(Const.PATH_CHECKSESSION, "false");
}
}
private void createServiceCenterTask() {
MicroserviceServiceCenterTask task =
new MicroserviceServiceCenterTask(eventBus, serviceRegistryConfig, srClient, microservice);
serviceCenterTask = new ServiceCenterTask(eventBus, serviceRegistryConfig.getHeartbeatInterval(),
serviceRegistryConfig.getResendHeartBeatTimes(), task);
}
public boolean unregisterInstance() {
MicroserviceInstance microserviceInstance = microservice.getInstance();
if (microserviceInstance.getInstanceId() == null || microserviceInstance.getServiceId() == null) {
return true;
}
boolean result = srClient.unregisterMicroserviceInstance(microserviceInstance.getServiceId(),
microserviceInstance.getInstanceId());
if (!result) {
LOGGER.error("Unregister microservice instance failed. microserviceId={} instanceId={}",
microserviceInstance.getServiceId(),
microserviceInstance.getInstanceId());
return false;
}
LOGGER.info("Unregister microservice instance success. microserviceId={} instanceId={}",
microserviceInstance.getServiceId(),
microserviceInstance.getInstanceId());
return true;
}
@Override
public List<MicroserviceInstance> findServiceInstance(String appId, String serviceName,
String versionRule) {
MicroserviceInstances instances = findServiceInstances(appId, serviceName, versionRule);
if (instances == null || instances.isMicroserviceNotExist()) {
return null;
}
return instances.getInstancesResponse().getInstances();
}
@Override
public MicroserviceInstances findServiceInstances(String appId, String serviceName,
String versionRule) {
MicroserviceCache microserviceCache = serviceRegistryCache
.findServiceCache(MicroserviceCacheKey.builder()
.serviceName(serviceName).appId(appId)
.env(microservice.getEnvironment())
.versionRule(versionRule)
.build());
return RegistryUtils.convertCacheToMicroserviceInstances(microserviceCache);
}
@Override
public MicroserviceCache findMicroserviceCache(MicroserviceCacheKey microserviceCacheKey) {
return serviceRegistryCache.findServiceCache(microserviceCacheKey);
}
@Override
public boolean updateMicroserviceProperties(Map<String, String> properties) {
boolean success = srClient.updateMicroserviceProperties(microservice.getServiceId(),
properties);
if (success) {
microservice.setProperties(properties);
}
return success;
}
@Override
public boolean updateInstanceProperties(Map<String, String> instanceProperties) {
MicroserviceInstance microserviceInstance = microservice.getInstance();
boolean success = srClient.updateInstanceProperties(microserviceInstance.getServiceId(),
microserviceInstance.getInstanceId(),
instanceProperties);
if (success) {
microserviceInstance.setProperties(instanceProperties);
}
return success;
}
public Microservice getRemoteMicroservice(String microserviceId) {
return srClient.getMicroservice(microserviceId);
}
@Override
public Microservice getAggregatedRemoteMicroservice(String microserviceId) {
return srClient.getAggregatedMicroservice(microserviceId);
}
public Microservice getMicroservice() {
return microservice;
}
public List<Microservice> getAllMicroservices() {
return srClient.getAllMicroservices();
}
public MicroserviceInstance getMicroserviceInstance() {
return microservice.getInstance();
}
public void destroy() {
eventBus.post(new ShutdownEvent());
unregisterInstance();
}
@Override
public String getName() {
return name;
}
void setName(String name) {
RegistryUtils.validateRegistryName(name);
this.name = name;
}
public ServiceRegistryCache getServiceRegistryCache() {
return serviceRegistryCache;
}
@Subscribe
public void onShutdown(ShutdownEvent event) {
LOGGER.info("service center task is shutdown.");
executorService.shutdownNow();
}
// post from watch eventloop, should refresh the exact microservice instances immediately
@Subscribe
public void onMicroserviceInstanceChanged(MicroserviceInstanceChangedEvent changedEvent) {
executorService.execute(new SuppressedRunnableWrapper(
() -> {
serviceRegistryCache.onMicroserviceInstanceChanged(changedEvent);
DiscoveryManager.INSTANCE.getAppManager().onMicroserviceInstanceChanged(changedEvent);
}));
}
// post from watch eventloop, should refresh all instances immediately
@Subscribe
public void serviceRegistryRecovery(RecoveryEvent event) {
executorService.execute(() -> {
serviceRegistryCache.forceRefreshCache();
DiscoveryManager.INSTANCE.getAppManager().pullInstances();
});
}
@Subscribe
public void onSafeModeChanged(SafeModeChangeEvent modeChangeEvent) {
executorService.execute(() -> {
LOGGER.warn("receive SafeModeChangeEvent, current mode={}", modeChangeEvent.getCurrentMode());
serviceRegistryCache.onSafeModeChanged(modeChangeEvent);
DiscoveryManager.INSTANCE.getAppManager().onSafeModeChanged(modeChangeEvent);
});
}
}