Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dubbo向polaris注册服务时,能够把{application}注册为服务、把接口注册为{application}的别称。 #31

Open
wants to merge 2 commits into
base: dubbo-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

import com.tencent.polaris.dubbo.servicealias.RegistryServiceAliasOperator;
import com.tencent.polaris.dubbo.servicealias.ServiceAlias;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
Expand Down Expand Up @@ -121,8 +124,11 @@ public void doRegister(URL url) {
if (port > 0) {
int weight = url.getParameter(Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
String version = url.getParameter(CommonConstants.VERSION_KEY, "");
polarisOperator.register(url.getServiceInterface(), url.getHost(), port, url.getProtocol(), version, weight,
metadata);
polarisOperator.register(RegistryServiceAliasOperator.getService(url), url.getHost(), port,
url.getProtocol(), version, weight, metadata);
if (RegistryServiceAliasOperator.enabled()) {
RegistryServiceAliasOperator.saveServiceAlias(new ServiceAlias(url));
}
registeredInstances.add(url);
} else {
LOGGER.warn("[POLARIS] skip register url {} for zero port value", url);
Expand All @@ -141,7 +147,7 @@ public void doUnregister(URL url) {
LOGGER.info("[POLARIS] unregister service from polaris: {}", url.toString());
int port = url.getPort();
if (port > 0) {
polarisOperator.deregister(url.getServiceInterface(), url.getHost(), url.getPort());
polarisOperator.deregister(RegistryServiceAliasOperator.getService(url), url.getHost(), url.getPort());
registeredInstances.remove(url);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.tencent.polaris.dubbo.registry;


import com.tencent.polaris.dubbo.servicealias.RegistryServiceAliasOperator;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
Expand All @@ -25,6 +26,7 @@ public class PolarisRegistryFactory extends AbstractRegistryFactory {

@Override
protected Registry createRegistry(URL url) {
url = RegistryServiceAliasOperator.setup(url);
PolarisRegistry polarisRegistry = new PolarisRegistry(url);
return polarisRegistry;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.tencent.polaris.dubbo.servicealias;

import org.apache.dubbo.common.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

/**
* @author <a href="mailto:[email protected]">amyson</a>
*/
public class RegistryServiceAliasOperator {
public static String KEY_Polaris_Rest_Token = "token";
public static String KEY_Polaris_Rest_Port = "port";

private static final Logger LOGGER = LoggerFactory.getLogger(RegistryServiceAliasOperator.class);
static String aliasUrl = null;
static String token = null;

public static URL setup(URL registryUrl) {
token = registryUrl.getParameter(KEY_Polaris_Rest_Token);
if (token == null)
return registryUrl;

String port = registryUrl.getParameter(KEY_Polaris_Rest_Port, "8090");
token = URLDecoder.decode(token);
aliasUrl = String.format("http://%s:%s/naming/v1/service/alias", registryUrl.getHost(), port);
LOGGER.info("[POLARIS] register dubbo service with alias enabled");
return registryUrl.removeParameter(KEY_Polaris_Rest_Token);
}

public static boolean enabled() {
return token != null;
}

public static String getService(URL svrUrl) {
return enabled() ? ServiceAlias.getApplication(svrUrl) : svrUrl.getServiceInterface();
}

public static void saveServiceAlias(ServiceAlias alias) {
if (!enabled())
return;

try {
post(aliasUrl, token, alias.toJson());
} catch (Exception ex) {
LOGGER.error("[POLARIS] save dubbo service alias %s error", alias.getAlias(), ex);
}
}

public static void post(String polarisUrl, String token, String body) throws Exception {
PrintWriter out = null;
BufferedReader in = null;
try {
java.net.URL url = new java.net.URL(polarisUrl);
URLConnection conn = url.openConnection();

conn.setRequestProperty("X-Polaris-Token", token);
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;)");
conn.setRequestProperty("Content-Type", "application/json"); // 设置内容类型

conn.setDoOutput(true);
conn.setDoInput(true);

out = new PrintWriter(conn.getOutputStream());
out.print(body);
out.flush();

in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
in.readLine();
} finally {
if (out != null)
out.close();
if (in != null) {
try {
in.close();
} catch (IOException ignore) {}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.tencent.polaris.dubbo.servicealias;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import org.apache.dubbo.common.URL;

/**
* @author <a href="mailto:[email protected]">amyson</a>
*/
public class ServiceAlias {
private String service;
private String namespace;
private String alias;
@JSONField(name = "alias_namespace")
private String aliasNamespace;

public ServiceAlias(URL url) {
this(url, "default");
}

public ServiceAlias(URL url, String namespace) {
this(url, namespace, namespace);
}

public ServiceAlias(URL url, String namespace, String aliasNamespace) {
this.service = getApplication(url);
this.namespace = namespace;
this.alias = url.getServiceInterface();
this.aliasNamespace = aliasNamespace;
}

public static String getApplication(URL url) {
return url.getParameter("application");
}

public String toJson() {
return JSON.toJSONString(this);
}

public String getService() {
return service;
}

public String getNamespace() {
return namespace;
}

public String getAlias() {
return alias;
}

public String getAliasNamespace() {
return aliasNamespace;
}
}
5 changes: 5 additions & 0 deletions dubbo/dubbo-plugins/dubbo-router-polaris/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
<artifactId>dubbo-router-polaris</artifactId>

<dependencies>
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>polaris-all</artifactId>
<version>${polaris.version}</version>
</dependency>
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>dubbo-registry-polaris</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public PolarisRouter(URL url) {
url.getParameters());
this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
routeRuleHandler = new RuleHandler();
polarisOperator = PolarisOperators.INSTANCE.getPolarisOperator(url.getHost(), url.getPort());
polarisOperator = PolarisOperators.INSTANCE.getFirstPolarisOperator(); //这里url是provider,根据地址信息是获取不到的
parser = QueryParser.load();
}

Expand Down
7 changes: 7 additions & 0 deletions polaris-adapter-dubbo/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@
<dependency>
<groupId>com.tencent.polaris</groupId>
<artifactId>polaris-all</artifactId>
<version>${polaris.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.21.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package com.tencent.polaris.common.parser;

import java.util.Iterator;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
Expand All @@ -28,13 +29,13 @@ public interface QueryParser {
String name();

static QueryParser load() {
ServiceLoader<QueryParser> loader = ServiceLoader.load(QueryParser.class);
QueryParser instance = loader.iterator().next();
Iterator<QueryParser> queryParserIter = ServiceLoader.load(QueryParser.class).iterator();
QueryParser instance = queryParserIter.hasNext() ? queryParserIter.next() : null;
if (Objects.nonNull(instance)) {
return instance;
}
String parser = System.getProperty("dubbo.polaris.query_parser");
if (parser.equals("JsonPath")) {
if ("JsonPath".equals(parser)) {
return new JsonPathQueryParser();
}
return new JavaObjectQueryParser();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
import com.tencent.polaris.specification.api.v1.model.ModelProto;
import com.tencent.polaris.specification.api.v1.traffic.manage.RateLimitProto;
import com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto;
import com.google.protobuf.StringValue;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
Expand All @@ -39,18 +41,43 @@ public class RuleHandler {

private final Object lock = new Object();


static Method getRevision;
static {
/* 直接调用 getRevision() 方法会抛出异常:
java.lang.NoSuchMethodError: com.tencent.polaris.specification.api.v1.traffic.manage.RoutingProto$Routing.getRevision()Lshade/polaris/com/google/protobuf/StringValue;
暂时通过反射调用方法.
*/
try {
getRevision = RoutingProto.Routing.class.getMethod("getRevision");
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static String getRevision(RoutingProto.Routing routing) {
try {
Object revision = getRevision.invoke(routing);
if (revision instanceof StringValue)
return ((StringValue) revision).getValue();
return revision.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public Set<String> getRouteLabels(RoutingProto.Routing routing) {
TimedCache<Set<String>> setTimedCache = routeRuleMatchLabels.get(routing.getRevision().getValue());
String revision = getRevision(routing);
TimedCache<Set<String>> setTimedCache = routeRuleMatchLabels.get(revision);
if (null != setTimedCache && !setTimedCache.isExpired()) {
return setTimedCache.getValue();
}
synchronized (lock) {
setTimedCache = routeRuleMatchLabels.get(routing.getRevision().getValue());
setTimedCache = routeRuleMatchLabels.get(revision);
if (null != setTimedCache && !setTimedCache.isExpired()) {
return setTimedCache.getValue();
}
TimedCache<Set<String>> timedCache = new TimedCache<>(buildRouteLabels(routing));
routeRuleMatchLabels.put(routing.getRevision().getValue(), timedCache);
routeRuleMatchLabels.put(revision, timedCache);
return timedCache.getValue();
}
}
Expand Down
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

<properties>
<!-- Project revision -->
<revision>0.2.2</revision>
<revision>0.3.0-20230901</revision>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
Expand All @@ -52,7 +52,7 @@
<maven.gpg.plugin.version>3.0.1</maven.gpg.plugin.version>
<maven.deploy.plugin.version>3.0.0-M1</maven.deploy.plugin.version>
<maven.flatten.plugin.version>1.2.5</maven.flatten.plugin.version>
<polaris.version>1.12.10</polaris.version>
<polaris.version>1.13.0</polaris.version>
<slf4j.version>1.7.25</slf4j.version>
<json_path_version>2.8.0</json_path_version>
</properties>
Expand Down