forked from apache/dubbo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
InMemoryWritableMetadataService.java
238 lines (201 loc) · 8.95 KB
/
InMemoryWritableMetadataService.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
/*
* 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.dubbo.metadata.store;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.WritableMetadataService;
import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder;
import org.apache.dubbo.metadata.definition.model.ServiceDefinition;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import com.google.gson.Gson;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static java.util.Collections.emptySortedSet;
import static java.util.Collections.unmodifiableSortedSet;
import static org.apache.dubbo.common.URL.buildKey;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
/**
* The {@link WritableMetadataService} implementation stores the metadata of Dubbo services in memory locally when they
* exported. It is used by server (provider).
*
* @see MetadataService
* @see WritableMetadataService
* @since 2.7.5
*/
public class InMemoryWritableMetadataService implements WritableMetadataService {
final Logger logger = LoggerFactory.getLogger(getClass());
private final Lock lock = new ReentrantLock();
// =================================== Registration =================================== //
/**
* All exported {@link URL urls} {@link Map} whose key is the return value of {@link URL#getServiceKey()} method
* and value is the {@link SortedSet sorted set} of the {@link URL URLs}
*/
ConcurrentNavigableMap<String, SortedSet<URL>> exportedServiceURLs = new ConcurrentSkipListMap<>();
// ==================================================================================== //
// =================================== Subscription =================================== //
/**
* The subscribed {@link URL urls} {@link Map} of {@link MetadataService},
* whose key is the return value of {@link URL#getServiceKey()} method and value is
* the {@link SortedSet sorted set} of the {@link URL URLs}
*/
ConcurrentNavigableMap<String, SortedSet<URL>> subscribedServiceURLs = new ConcurrentSkipListMap<>();
ConcurrentNavigableMap<String, String> serviceDefinitions = new ConcurrentSkipListMap<>();
@Override
public SortedSet<String> getSubscribedURLs() {
return getAllUnmodifiableServiceURLs(subscribedServiceURLs);
}
private SortedSet<String> getAllUnmodifiableServiceURLs(Map<String, SortedSet<URL>> serviceURLs) {
SortedSet<URL> bizURLs = new TreeSet<>(InMemoryWritableMetadataService.URLComparator.INSTANCE);
for (Map.Entry<String, SortedSet<URL>> entry : serviceURLs.entrySet()) {
SortedSet<URL> urls = entry.getValue();
if (urls != null) {
for (URL url : urls) {
if (!MetadataService.class.getName().equals(url.getServiceInterface())) {
bizURLs.add(url);
}
}
}
}
return MetadataService.toSortedStrings(bizURLs);
}
@Override
public SortedSet<String> getExportedURLs(String serviceInterface, String group, String version, String protocol) {
if (ALL_SERVICE_INTERFACES.equals(serviceInterface)) {
return getAllUnmodifiableServiceURLs(exportedServiceURLs);
}
String serviceKey = buildKey(serviceInterface, group, version);
return unmodifiableSortedSet(getServiceURLs(exportedServiceURLs, serviceKey, protocol));
}
@Override
public boolean exportURL(URL url) {
return addURL(exportedServiceURLs, url);
}
@Override
public boolean unexportURL(URL url) {
return removeURL(exportedServiceURLs, url);
}
@Override
public boolean subscribeURL(URL url) {
return addURL(subscribedServiceURLs, url);
}
@Override
public boolean unsubscribeURL(URL url) {
return removeURL(subscribedServiceURLs, url);
}
@Override
public void publishServiceDefinition(URL providerUrl) {
try {
if(!ProtocolUtils.isGeneric(providerUrl.getParameter(GENERIC_KEY))){
String interfaceName = providerUrl.getParameter(INTERFACE_KEY);
if (StringUtils.isNotEmpty(interfaceName)) {
Class interfaceClass = Class.forName(interfaceName);
ServiceDefinition serviceDefinition = ServiceDefinitionBuilder.build(interfaceClass);
Gson gson = new Gson();
String data = gson.toJson(serviceDefinition);
serviceDefinitions.put(providerUrl.getServiceKey(), data);
return;
}
logger.error("publishProvider interfaceName is empty . providerUrl: " + providerUrl.toFullString());
}
} catch (ClassNotFoundException e) {
//ignore error
logger.error("publishProvider getServiceDescriptor error. providerUrl: " + providerUrl.toFullString(), e);
}
}
@Override
public String getServiceDefinition(String interfaceName, String version, String group) {
return serviceDefinitions.get(URL.buildKey(interfaceName, group, version));
}
@Override
public String getServiceDefinition(String serviceKey) {
return serviceDefinitions.get(serviceKey);
}
boolean addURL(Map<String, SortedSet<URL>> serviceURLs, URL url) {
return executeMutually(() -> {
SortedSet<URL> urls = serviceURLs.computeIfAbsent(url.getServiceKey(), this::newSortedURLs);
// make sure the parameters of tmpUrl is variable
return urls.add(url);
});
}
boolean removeURL(Map<String, SortedSet<URL>> serviceURLs, URL url) {
return executeMutually(() -> {
String key = url.getServiceKey();
SortedSet<URL> urls = serviceURLs.getOrDefault(key, null);
if (urls == null) {
return true;
}
boolean r = urls.remove(url);
// if it is empty
if (urls.isEmpty()) {
serviceURLs.remove(key);
}
return r;
});
}
private SortedSet<URL> newSortedURLs(String serviceKey) {
return new TreeSet<>(InMemoryWritableMetadataService.URLComparator.INSTANCE);
}
boolean executeMutually(Callable<Boolean> callable) {
boolean success = false;
try {
lock.lock();
try {
success = callable.call();
} catch (Exception e) {
if (logger.isErrorEnabled()) {
logger.error(e);
}
}
} finally {
lock.unlock();
}
return success;
}
private SortedSet<String> getServiceURLs(Map<String, SortedSet<URL>> exportedServiceURLs, String serviceKey,
String protocol) {
SortedSet<URL> serviceURLs = exportedServiceURLs.get(serviceKey);
if (isEmpty(serviceURLs)) {
return emptySortedSet();
}
return MetadataService.toSortedStrings(serviceURLs.stream().filter(url -> isAcceptableProtocol(protocol, url)));
}
private boolean isAcceptableProtocol(String protocol, URL url) {
return protocol == null
|| protocol.equals(url.getParameter(PROTOCOL_KEY))
|| protocol.equals(url.getProtocol());
}
static class URLComparator implements Comparator<URL> {
public static final URLComparator INSTANCE = new URLComparator();
@Override
public int compare(URL o1, URL o2) {
return o1.toFullString().compareTo(o2.toFullString());
}
}
}