1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

#734 -> update maven coordinates

This commit is contained in:
fangjian0423
2019-07-08 11:38:27 +08:00
parent 3998ea23f7
commit aa03ddbbe2
498 changed files with 1208 additions and 1203 deletions

View File

@@ -0,0 +1,71 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alicloud.ans.registry.AnsAutoServiceRegistration;
import org.springframework.cloud.alicloud.ans.registry.AnsRegistration;
import org.springframework.cloud.alicloud.ans.registry.AnsServiceRegistry;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author xiaolongzuo
*/
@Configuration
@EnableConfigurationProperties
@ConditionalOnClass(name = "org.springframework.boot.web.context.WebServerInitializedEvent")
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@ConditionalOnAnsEnabled
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
AutoServiceRegistrationAutoConfiguration.class })
public class AnsAutoConfiguration {
@Bean
public AnsServiceRegistry ansServiceRegistry() {
return new AnsServiceRegistry();
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public AnsRegistration ansRegistration(AnsProperties ansProperties,
ApplicationContext applicationContext) {
return new AnsRegistration(ansProperties, applicationContext);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public AnsAutoServiceRegistration ansAutoServiceRegistration(
AnsServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
AnsRegistration registration) {
return new AnsAutoServiceRegistration(registry, autoServiceRegistrationProperties,
registration);
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import java.util.*;
/**
* @author xiaolongzuo
* @author pbting
*/
public class AnsDiscoveryClient implements DiscoveryClient {
public static final String DESCRIPTION = "Spring Cloud ANS Discovery Client";
@Override
public String description() {
return DESCRIPTION;
}
@Override
public List<ServiceInstance> getInstances(String serviceId) {
try {
List<Host> hosts = NamingService.getHosts(serviceId);
return hostToServiceInstanceList(hosts, serviceId);
}
catch (Exception e) {
throw new RuntimeException(
"Can not get hosts from ans server. serviceId: " + serviceId, e);
}
}
private static ServiceInstance hostToServiceInstance(Host host, String serviceId) {
AnsServiceInstance ansServiceInstance = new AnsServiceInstance();
ansServiceInstance.setHost(host.getIp());
ansServiceInstance.setPort(host.getPort());
ansServiceInstance.setServiceId(serviceId);
Map<String, String> metadata = new HashMap<String, String>(5);
metadata.put("appUseType", host.getAppUseType());
metadata.put("site", host.getSite());
metadata.put("unit", host.getUnit());
metadata.put("doubleWeight", "" + host.getDoubleWeight());
metadata.put("weight", "" + host.getWeight());
ansServiceInstance.setMetadata(metadata);
return ansServiceInstance;
}
private static List<ServiceInstance> hostToServiceInstanceList(List<Host> hosts,
String serviceId) {
List<ServiceInstance> result = new ArrayList<ServiceInstance>(hosts.size());
for (Host host : hosts) {
result.add(hostToServiceInstance(host, serviceId));
}
return result;
}
@Override
public List<String> getServices() {
Set<String> publishers = NamingService.getPublishes();
Set<String> doms = NamingService.getDomsSubscribed();
doms.addAll(publishers);
List<String> result = new LinkedList<>();
for (String service : doms) {
result.add(service);
}
return result;
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author xiaolongzuo
* @author pbting
*/
@Configuration
@ConditionalOnMissingBean(DiscoveryClient.class)
@EnableConfigurationProperties
@AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class)
public class AnsDiscoveryClientAutoConfiguration {
@Bean
public DiscoveryClient ansDiscoveryClient() {
return new AnsDiscoveryClient();
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans;
import java.net.URI;
import java.util.Map;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
/**
* @author xiaolongzuo
*/
public class AnsServiceInstance implements ServiceInstance {
private String serviceId;
private String host;
private int port;
private boolean secure;
private Map<String, String> metadata;
@Override
public String getServiceId() {
return serviceId;
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public boolean isSecure() {
return secure;
}
@Override
public URI getUri() {
return DefaultServiceInstance.getUri(this);
}
@Override
public Map<String, String> getMetadata() {
return metadata;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setSecure(boolean secure) {
this.secure = secure;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* @author xiaolongzuo
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@ConditionalOnProperty(value = "spring.cloud.ans.enabled", matchIfMissing = true)
public @interface ConditionalOnAnsEnabled {
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.endpoint;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author xiaolongzuo
* @author pbting
*/
@Endpoint(id = "ans")
public class AnsEndpoint {
private static final Logger log = LoggerFactory.getLogger(AnsEndpoint.class);
private AnsProperties ansProperties;
public AnsEndpoint(AnsProperties ansProperties) {
this.ansProperties = ansProperties;
}
/**
* @return ans endpoint
*/
@ReadOperation
public Map<String, Object> invoke() {
Map<String, Object> ansEndpoint = new HashMap<>();
log.info("ANS endpoint invoke, ansProperties is " + ansProperties);
ansEndpoint.put("ansProperties", ansProperties);
Map<String, Object> subscribes = new HashMap<>();
Set<String> subscribeServices = NamingService.getDomsSubscribed();
for (String service : subscribeServices) {
try {
List<Host> hosts = NamingService.getHosts(service);
subscribes.put(service, hosts);
}
catch (Exception ignoreException) {
}
}
ansEndpoint.put("subscribes", subscribes);
log.info("ANS endpoint invoke, subscribes is " + subscribes);
return ansEndpoint;
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.endpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.context.annotation.Bean;
/**
* @author xiaolongzuo
*/
@ConditionalOnWebApplication
@ConditionalOnClass(Endpoint.class)
public class AnsEndpointAutoConfiguration {
@Bean
public AnsEndpoint ansEndpoint(AnsProperties ansProperties) {
return new AnsEndpoint(ansProperties);
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* @author xiaolongzuo
* @author pbting
*/
public class AnsAutoServiceRegistration
extends AbstractAutoServiceRegistration<AnsRegistration> {
private static final Logger log = LoggerFactory
.getLogger(AnsAutoServiceRegistration.class);
private AnsRegistration registration;
public AnsAutoServiceRegistration(ServiceRegistry<AnsRegistration> serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
AnsRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties);
this.registration = registration;
}
@Deprecated
public void setPort(int port) {
getPort().set(port);
}
@Override
protected AnsRegistration getRegistration() {
if (this.registration.getPort() < 0 && this.getPort().get() > 0) {
this.registration.setPort(this.getPort().get());
}
Assert.isTrue(this.registration.getPort() > 0, "service.port has not been set");
return this.registration;
}
@Override
protected AnsRegistration getManagementRegistration() {
return null;
}
@Override
protected void register() {
if (!this.registration.getAnsProperties().isRegisterEnabled()) {
log.debug("Registration disabled.");
return;
}
if (this.registration.getPort() < 0) {
this.registration.setPort(getPort().get());
}
super.register();
}
@Override
protected void registerManagement() {
if (!this.registration.getAnsProperties().isRegisterEnabled()) {
return;
}
super.registerManagement();
}
@Override
protected Object getConfiguration() {
return this.registration.getAnsProperties();
}
@Override
protected boolean isEnabled() {
return this.registration.getAnsProperties().isRegisterEnabled();
}
@Override
@SuppressWarnings("deprecation")
protected String getAppName() {
String appName = registration.getServiceId();
return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
}
}

View File

@@ -0,0 +1,138 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.ManagementServerPortUtils;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.Map;
/**
* @author xiaolongzuo
*/
public class AnsRegistration implements Registration, ServiceInstance {
static final String MANAGEMENT_PORT = "management.port";
static final String MANAGEMENT_CONTEXT_PATH = "management.context-path";
static final String MANAGEMENT_ADDRESS = "management.address";
static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path";
private AnsProperties ansProperties;
private ApplicationContext context;
public AnsRegistration(AnsProperties ansProperties, ApplicationContext context) {
this.ansProperties = ansProperties;
this.context = context;
}
@PostConstruct
public void init() {
Map<String, String> metadata = ansProperties.getClientMetadata();
Environment env = context.getEnvironment();
String endpointBasePath = env.getProperty(MANAGEMENT_ENDPOINT_BASE_PATH);
if (!StringUtils.isEmpty(endpointBasePath)) {
metadata.put(MANAGEMENT_ENDPOINT_BASE_PATH, endpointBasePath);
}
Integer managementPort = ManagementServerPortUtils.getPort(context);
if (null != managementPort) {
metadata.put(MANAGEMENT_PORT, managementPort.toString());
String contextPath = env
.getProperty("management.server.servlet.context-path");
String address = env.getProperty("management.server.address");
if (!StringUtils.isEmpty(contextPath)) {
metadata.put(MANAGEMENT_CONTEXT_PATH, contextPath);
}
if (!StringUtils.isEmpty(address)) {
metadata.put(MANAGEMENT_ADDRESS, address);
}
}
}
@Override
public String getServiceId() {
return ansProperties.getClientDomains();
}
@Override
public String getHost() {
return ansProperties.getClientIp();
}
@Override
public int getPort() {
return ansProperties.getClientPort();
}
public void setPort(int port) {
// if spring.cloud.ans.port is not set,use the port detected from context
if (ansProperties.getClientPort() < 0) {
this.ansProperties.setClientPort(port);
}
}
@Override
public boolean isSecure() {
return ansProperties.isSecure();
}
@Override
public URI getUri() {
return DefaultServiceInstance.getUri(this);
}
@Override
public Map<String, String> getMetadata() {
return ansProperties.getClientMetadata();
}
public boolean isRegisterEnabled() {
return ansProperties.isRegisterEnabled();
}
public String getCluster() {
return ansProperties.getClientCluster();
}
public float getRegisterWeight(String dom) {
if (null != ansProperties.getClientWeights().get(dom)
&& ansProperties.getClientWeights().get(dom) > 0) {
return ansProperties.getClientWeights().get(dom);
}
return ansProperties.getClientWeight();
}
public AnsProperties getAnsProperties() {
return ansProperties;
}
@Override
public String toString() {
return "AnsRegistration{" + "ansProperties=" + ansProperties + '}';
}
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author xiaolongzuo
*/
public class AnsServiceRegistry implements ServiceRegistry<AnsRegistration> {
private static final Logger log = LoggerFactory.getLogger(AnsServiceRegistry.class);
private static final String SEPARATOR = ",";
@Override
public void register(AnsRegistration registration) {
if (!registration.isRegisterEnabled()) {
log.warn("Registration is disabled...");
return;
}
if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No service to register for client...");
return;
}
List<NodeReactor.Tag> tags = new ArrayList<>();
for (Map.Entry<String, String> entry : registration.getAnsProperties().getTags()
.entrySet()) {
NodeReactor.Tag tag = new NodeReactor.Tag();
tag.setName(entry.getKey());
tag.setValue(entry.getValue());
tags.add(tag);
}
for (String dom : registration.getServiceId().split(SEPARATOR)) {
try {
NamingService.regDom(dom, registration.getHost(), registration.getPort(),
registration.getRegisterWeight(dom), registration.getCluster(),
tags);
log.info("INFO_ANS_REGISTER, {} {}:{} register finished", dom,
registration.getAnsProperties().getClientIp(),
registration.getAnsProperties().getClientPort());
}
catch (Exception e) {
log.error("ERR_ANS_REGISTER, {} register failed...{},", dom,
registration.toString(), e);
}
}
}
@Override
public void deregister(AnsRegistration registration) {
log.info("De-registering from ANSServer now...");
if (StringUtils.isEmpty(registration.getServiceId())) {
log.warn("No dom to de-register for client...");
return;
}
try {
NamingService.deRegDom(registration.getServiceId(), registration.getHost(),
registration.getPort(), registration.getCluster());
}
catch (Exception e) {
log.error("ERR_ANS_DEREGISTER, de-register failed...{},",
registration.toString(), e);
}
log.info("De-registration finished.");
}
@Override
public void close() {
}
@Override
public void setStatus(AnsRegistration registration, String status) {
}
@Override
public <T> T getStatus(AnsRegistration registration) {
return null;
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author xiaolongzuo
* @author pbting
*/
@Configuration
public class AnsRibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ServerList<?> ansRibbonServerList(IClientConfig config) {
AnsServerList serverList = new AnsServerList(config.getClientName());
return serverList;
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import java.util.Collections;
import java.util.Map;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import com.netflix.loadbalancer.Server;
/**
* @author xiaolongzuo
*/
public class AnsServer extends Server {
private final MetaInfo metaInfo;
private final Host host;
private final Map<String, String> metadata;
public AnsServer(final Host host, final String dom) {
super(host.getIp(), host.getPort());
this.host = host;
this.metadata = Collections.emptyMap();
metaInfo = new MetaInfo() {
@Override
public String getAppName() {
return dom;
}
@Override
public String getServerGroup() {
return getMetadata().get("group");
}
@Override
public String getServiceIdForDiscovery() {
return dom;
}
@Override
public String getInstanceId() {
return AnsServer.this.host.getIp() + ":" + dom + ":"
+ AnsServer.this.host.getPort();
}
};
}
@Override
public MetaInfo getMetaInfo() {
return metaInfo;
}
public Host getHealthService() {
return this.host;
}
public Map<String, String> getMetadata() {
return metadata;
}
@Override
public String toString() {
return "AnsServer{" + "metaInfo=" + metaInfo + ", host=" + host + ", metadata="
+ metadata + '}';
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
/**
* @author xiaolongzuo
*/
public class AnsServerList extends AbstractServerList<AnsServer> {
private String dom;
public AnsServerList(String dom) {
this.dom = dom;
}
@Override
public List<AnsServer> getInitialListOfServers() {
try {
List<Host> hosts = NamingService.getHosts(getDom());
return hostsToServerList(hosts);
}
catch (Exception e) {
throw new IllegalStateException("Can not get ans hosts, dom=" + getDom(), e);
}
}
@Override
public List<AnsServer> getUpdatedListOfServers() {
return getInitialListOfServers();
}
private AnsServer hostToServer(Host host) {
AnsServer server = new AnsServer(host, getDom());
return server;
}
private List<AnsServer> hostsToServerList(List<Host> hosts) {
List<AnsServer> result = new ArrayList<AnsServer>(hosts.size());
for (Host host : hosts) {
if (host.isValid()) {
result.add(hostToServer(host));
}
}
return result;
}
public String getDom() {
return dom;
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
this.dom = iClientConfig.getClientName();
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
/**
* @author xiaolongzuo
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@ConditionalOnProperty(value = "ribbon.ans.enabled", matchIfMissing = true)
public @interface ConditionalOnRibbonAns {
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.alicloud.ans.ConditionalOnAnsEnabled;
import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Configuration;
/**
* @author xiaolongzuo
*/
@Configuration
@EnableConfigurationProperties
@ConditionalOnAnsEnabled
@ConditionalOnBean(SpringClientFactory.class)
@ConditionalOnRibbonAns
@AutoConfigureAfter(RibbonAutoConfiguration.class)
@RibbonClients(defaultConfiguration = AnsRibbonClientConfiguration.class)
public class RibbonAnsAutoConfiguration {
}

View File

@@ -0,0 +1,5 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alicloud.ans.endpoint.AnsEndpointAutoConfiguration,\
org.springframework.cloud.alicloud.ans.ribbon.RibbonAnsAutoConfiguration,\
org.springframework.cloud.alicloud.ans.AnsAutoConfiguration,\
org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration

View File

@@ -0,0 +1,116 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.cloud.client.ServiceInstance;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(NamingService.class)
public class AnsDiscoveryClientTests {
private String host = "123.123.123.123";
private int port = 8888;
private String serviceName = "test-service";
@Test
public void testGetServers() throws Exception {
ArrayList<Host> hosts = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("test-key", "test-value");
map.put("secure", "true");
hosts.add(hostInstance(serviceName, false, host, port, map));
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(eq(serviceName))).thenReturn(hosts);
AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient();
List<ServiceInstance> serviceInstances = discoveryClient
.getInstances(serviceName);
assertThat(serviceInstances.size()).isEqualTo(1);
ServiceInstance serviceInstance = serviceInstances.get(0);
assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName);
assertThat(serviceInstance.getHost()).isEqualTo(host);
assertThat(serviceInstance.getPort()).isEqualTo(port);
// assertThat(serviceInstance.isSecure()).isEqualTo(true);
// ans doesn't support metadata
assertThat(serviceInstance.getUri().toString())
.isEqualTo(getUri(serviceInstance));
// assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value");
// ans doesn't support metadata
}
@Test
public void testGetAllService() throws Exception {
Set<String> subscribedServices = new HashSet<>();
subscribedServices.add(serviceName + "1");
subscribedServices.add(serviceName + "2");
subscribedServices.add(serviceName + "3");
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getDomsSubscribed()).thenReturn(subscribedServices);
AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient();
List<String> services = discoveryClient.getServices();
assertThat(services.size()).isEqualTo(3);
assertThat(services.contains(serviceName + "1"));
assertThat(services.contains(serviceName + "2"));
assertThat(services.contains(serviceName + "3"));
}
private String getUri(ServiceInstance instance) {
if (instance.isSecure()) {
return "https://" + host + ":" + port;
}
return "http://" + host + ":" + port;
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsAutoServiceRegistrationEnabledTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.server-port=8080",
"spring.cloud.alicloud.ans.register-enabled=false" }, webEnvironment = RANDOM_PORT)
public class AnsAutoServiceRegistrationEnabledTests {
@Autowired
private AnsRegistration registration;
@Autowired
private AnsAutoServiceRegistration ansAutoServiceRegistration;
@Autowired
private AnsProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("AnsRegistration was not created", registration);
assertNotNull("AnsProperties was not created", properties);
assertNotNull("AnsAutoServiceRegistration was not created",
ansAutoServiceRegistration);
checkEnabled();
}
private void checkEnabled() {
assertFalse("Ans Auto Registration should not start",
ansAutoServiceRegistration.isEnabled());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT)
public class AnsAutoServiceRegistrationIpNetworkInterfaceTests {
@Autowired
private AnsRegistration registration;
@Autowired
private AnsAutoServiceRegistration ansAutoServiceRegistration;
@Autowired
private AnsProperties properties;
@Autowired
private InetUtils inetUtils;
@Test
public void contextLoads() throws Exception {
assertNotNull("AnsRegistration was not created", registration);
assertNotNull("AnsProperties was not created", properties);
assertNotNull("AnsAutoServiceRegistration was not created",
ansAutoServiceRegistration);
checkoutAnsDiscoveryServiceIP();
}
private void checkoutAnsDiscoveryServiceIP() {
assertEquals("AnsProperties service IP was wrong",
getIPFromNetworkInterface(TestConfig.netWorkInterfaceName),
registration.getHost());
}
private String getIPFromNetworkInterface(String networkInterface) {
if (!TestConfig.hasValidNetworkInterface) {
return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
}
try {
NetworkInterface netInterface = NetworkInterface.getByName(networkInterface);
Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses();
while (inetAddress.hasMoreElements()) {
InetAddress currentAddress = inetAddress.nextElement();
if (currentAddress instanceof Inet4Address
&& !currentAddress.isLoopbackAddress()) {
return currentAddress.getHostAddress();
}
}
return networkInterface;
}
catch (Exception e) {
return networkInterface;
}
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
public static class TestConfig {
static boolean hasValidNetworkInterface = false;
static String netWorkInterfaceName;
static {
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface
.getNetworkInterfaces();
while (enumeration.hasMoreElements() && !hasValidNetworkInterface) {
NetworkInterface networkInterface = enumeration.nextElement();
Enumeration<InetAddress> inetAddress = networkInterface
.getInetAddresses();
while (inetAddress.hasMoreElements()) {
InetAddress currentAddress = inetAddress.nextElement();
if (currentAddress instanceof Inet4Address
&& !currentAddress.isLoopbackAddress()) {
hasValidNetworkInterface = true;
netWorkInterfaceName = networkInterface.getName();
System.setProperty(
"spring.cloud.alicloud.ans.client-interface-name",
networkInterface.getName());
break;
}
}
}
}
catch (Exception e) {
}
}
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsAutoServiceRegistrationIpTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.alicloud.ans.client-domains=myTestService2",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.client-weight=2",
"spring.cloud.alicloud.ans.server-port=8080",
"spring.cloud.alicloud.ans.client-ip=123.123.123.123" }, webEnvironment = RANDOM_PORT)
public class AnsAutoServiceRegistrationIpTests {
@Autowired
private AnsRegistration registration;
@Autowired
private AnsAutoServiceRegistration ansAutoServiceRegistration;
@Autowired
private AnsProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("AnsRegistration was not created", registration);
assertNotNull("AnsProperties was not created", properties);
assertNotNull("AnsAutoServiceRegistration was not created",
ansAutoServiceRegistration);
checkoutAnsDiscoveryServiceIP();
checkoutAnsDiscoveryServiceName();
checkoutAnsDiscoveryWeight();
}
private void checkoutAnsDiscoveryServiceIP() {
assertEquals("AnsProperties service IP was wrong", "123.123.123.123",
registration.getHost());
}
private void checkoutAnsDiscoveryServiceName() {
assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService2",
properties.getClientDomains());
}
private void checkoutAnsDiscoveryWeight() {
assertEquals(2L, properties.getClientWeight(), 0);
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_CONTEXT_PATH;
import static org.springframework.cloud.alicloud.ans.registry.AnsRegistration.MANAGEMENT_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService1", "management.server.port=8888",
"management.server.servlet.context-path=/test-context-path",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT)
public class AnsAutoServiceRegistrationManagementPortTests {
@Autowired
private AnsRegistration registration;
@Autowired
private AnsAutoServiceRegistration ansAutoServiceRegistration;
@Autowired
private AnsProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("AnsRegistration was not created", registration);
assertNotNull("AnsProperties was not created", properties);
assertNotNull("AnsAutoServiceRegistration was not created",
ansAutoServiceRegistration);
checkoutNacosDiscoveryManagementData();
}
private void checkoutNacosDiscoveryManagementData() {
assertEquals("AnsProperties management port was wrong", "8888",
properties.getClientMetadata().get(MANAGEMENT_PORT));
assertEquals("AnsProperties management context path was wrong",
"/test-context-path",
properties.getClientMetadata().get(MANAGEMENT_CONTEXT_PATH));
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsAutoServiceRegistrationPortTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.server-port=8080",
"spring.cloud.alicloud.ans.client-port=8888" }, webEnvironment = RANDOM_PORT)
public class AnsAutoServiceRegistrationPortTests {
@Autowired
private AnsRegistration registration;
@Autowired
private AnsAutoServiceRegistration ansAutoServiceRegistration;
@Autowired
private AnsProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("AnsRegistration was not created", registration);
assertNotNull("AnsDiscoveryProperties was not created", properties);
assertNotNull("AnsAutoServiceRegistration was not created",
ansAutoServiceRegistration);
checkoutAnsDiscoveryServicePort();
}
private void checkoutAnsDiscoveryServicePort() {
assertEquals("AnsDiscoveryProperties service Port was wrong", 8888,
registration.getPort());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,160 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.registry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.alicloud.ans.endpoint.AnsEndpoint;
import org.springframework.cloud.alicloud.context.ans.AnsProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsAutoServiceRegistrationTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.server-port=8080",
"spring.cloud.alicloud.ans.secure=true",
"spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT)
public class AnsAutoServiceRegistrationTests {
@Autowired
private AnsRegistration registration;
@Autowired
private AnsAutoServiceRegistration ansAutoServiceRegistration;
@LocalServerPort
private int port;
@Autowired
private AnsProperties properties;
@Autowired
private InetUtils inetUtils;
@Test
public void contextLoads() throws Exception {
assertNotNull("AnsRegistration was not created", registration);
assertNotNull("AnsProperties was not created", properties);
assertNotNull("AnsAutoServiceRegistration was not created",
ansAutoServiceRegistration);
checkoutAnsDiscoveryServerList();
checkoutAnsDiscoveryServerPort();
checkoutAnsDiscoveryServiceName();
checkoutAnsDiscoveryServiceIP();
checkoutAnsDiscoveryServicePort();
checkoutAnsDiscoverySecure();
checkAutoRegister();
checkoutEndpoint();
}
private void checkAutoRegister() {
assertTrue("Ans Auto Registration was not start",
ansAutoServiceRegistration.isRunning());
}
private void checkoutAnsDiscoveryServerList() {
assertEquals("AnsDiscoveryProperties server list was wrong", "127.0.0.1",
properties.getServerList());
}
private void checkoutAnsDiscoveryServerPort() {
assertEquals("AnsDiscoveryProperties server port was wrong", "8080",
properties.getServerPort());
}
private void checkoutAnsDiscoveryServiceName() {
assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService1",
properties.getClientDomains());
}
private void checkoutAnsDiscoveryServiceIP() {
assertEquals("AnsDiscoveryProperties service IP was wrong",
inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(),
registration.getHost());
}
private void checkoutAnsDiscoveryServicePort() {
assertEquals("AnsDiscoveryProperties service Port was wrong", port,
registration.getPort());
}
private void checkoutAnsDiscoverySecure() {
assertTrue("AnsDiscoveryProperties secure should be true", properties.isSecure());
}
private void checkoutEndpoint() throws Exception {
AnsEndpoint ansEndpoint = new AnsEndpoint(properties);
Map<String, Object> map = ansEndpoint.invoke();
assertEquals(map.get("ansProperties"), properties);
Map<String, Object> subscribes = new HashMap<>();
Set<String> subscribeServices = NamingService.getDomsSubscribed();
for (String service : subscribeServices) {
try {
List<Host> hosts = NamingService.getHosts(service);
subscribes.put(service, hosts);
}
catch (Exception ignoreException) {
}
}
assertEquals(map.get("subscribes"), subscribes);
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.alicloud.ans.AnsAutoConfiguration;
import org.springframework.cloud.alicloud.ans.AnsDiscoveryClientAutoConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.client.config.IClientConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
/**
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnsRibbonClientConfigurationTests.TestConfig.class, properties = {
"spring.application.name=myTestService1",
"spring.cloud.alicloud.ans.server-list=127.0.0.1",
"spring.cloud.alicloud.ans.server-port=8080",
"spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT)
public class AnsRibbonClientConfigurationTests {
@Autowired
private AnsServerList serverList;
@Test
public void contextLoads() throws Exception {
assertThat(serverList.getDom()).isEqualTo("myapp");
}
@Configuration
public static class AnsRibbonTestConfiguration {
@Bean
IClientConfig iClientConfig() {
DefaultClientConfigImpl config = new DefaultClientConfigImpl();
config.setClientName("myapp");
return config;
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class,
AnsRibbonTestConfiguration.class, RibbonAnsAutoConfiguration.class,
AnsRibbonClientConfiguration.class })
public static class TestConfig {
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.alicloud.ans.test.AnsMockTest.hostInstance;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.alibaba.ans.core.NamingService;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import com.netflix.client.config.IClientConfig;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ NamingService.class, AnsServer.class })
public class AnsServerListTests {
@Test
@SuppressWarnings("unchecked")
public void testEmptyInstancesReturnsEmptyList() throws Exception {
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(anyString())).thenReturn(Collections.EMPTY_LIST);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
AnsServerList serverList = new AnsServerList("test-service");
serverList.initWithNiwsConfig(clientConfig);
List<AnsServer> servers = serverList.getInitialListOfServers();
assertThat(servers).isEmpty();
}
@Test
@SuppressWarnings("unchecked")
public void testGetServers() throws Exception {
ArrayList<Host> hosts = new ArrayList<>();
hosts.add(hostInstance("test-service", true, Collections.emptyMap()));
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(anyString())).thenReturn(hosts);
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
AnsServerList serverList = new AnsServerList("test-service");
serverList.initWithNiwsConfig(clientConfig);
List<AnsServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1);
servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(1);
}
@Test
@SuppressWarnings("unchecked")
public void testGetServersWithInstanceStatus() throws Exception {
ArrayList<Host> hosts = new ArrayList<>();
HashMap<String, String> map1 = new HashMap<>();
map1.put("instanceNum", "1");
HashMap<String, String> map2 = new HashMap<>();
map2.put("instanceNum", "2");
hosts.add(hostInstance("test-service", false, map1));
hosts.add(hostInstance("test-service", true, map2));
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(eq("test-service"))).thenReturn(
hosts.stream().filter(Host::isValid).collect(Collectors.toList()));
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
AnsServerList serverList = new AnsServerList("test-service");
serverList.initWithNiwsConfig(clientConfig);
List<AnsServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1);
AnsServer ansServer = servers.get(0);
Host host = ansServer.getHealthService();
assertThat(ansServer.getMetaInfo().getInstanceId()).isEqualTo(
host.getIp() + ":" + host.getHostname() + ":" + host.getPort());
assertThat(ansServer.getHealthService().isValid()).isEqualTo(true);
assertThat(ansServer.getHealthService().getHostname()).isEqualTo("test-service");
}
@Test
public void testUpdateServers() throws Exception {
ArrayList<Host> hosts = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
map.put("instanceNum", "1");
hosts.add(hostInstance("test-service", true, map));
PowerMockito.mockStatic(NamingService.class);
when(NamingService.getHosts(eq("test-service"))).thenReturn(
hosts.stream().filter(Host::isValid).collect(Collectors.toList()));
IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service");
AnsServerList serverList = new AnsServerList("test-service");
serverList.initWithNiwsConfig(clientConfig);
List<AnsServer> servers = serverList.getUpdatedListOfServers();
assertThat(servers).hasSize(1);
assertThat(servers.get(0).getHealthService().isValid()).isEqualTo(true);
}
}

View File

@@ -0,0 +1,76 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.ribbon;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
import com.netflix.loadbalancer.Server;
/**
* @author xiaolongzuo
*/
public class AnsServiceListTests {
static final String IP_ADDR = "10.0.0.2";
static final int PORT = 8080;
@Test
public void testAnsServer() {
AnsServerList serverList = getAnsServerList();
List<AnsServer> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
Server des = assertAnsServer(servers);
assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort());
}
protected Server assertAnsServer(List<AnsServer> servers) {
Server actualServer = servers.get(0);
assertTrue("server was not a DomainExtractingServer",
actualServer instanceof AnsServer);
AnsServer des = AnsServer.class.cast(actualServer);
assertNotNull("host is null", des.getHealthService());
assertEquals("unit was wrong", "DEFAULT", des.getHealthService().getUnit());
return des;
}
protected AnsServerList getAnsServerList() {
Host host = mock(Host.class);
given(host.getIp()).willReturn(IP_ADDR);
given(host.getDoubleWeight()).willReturn(1.0);
given(host.getPort()).willReturn(PORT);
given(host.getWeight()).willReturn(1);
given(host.getUnit()).willReturn("DEFAULT");
AnsServer server = new AnsServer(host, "testDom");
@SuppressWarnings("unchecked")
AnsServerList originalServerList = mock(AnsServerList.class);
given(originalServerList.getInitialListOfServers())
.willReturn(Arrays.asList(server));
return originalServerList;
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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.springframework.cloud.alicloud.ans.test;
import java.util.Map;
import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host;
/**
* @author xiaojing
*/
public class AnsMockTest {
public static Host hostInstance(String serviceName, boolean valid,
Map<String, String> metadata) {
Host host = new Host();
host.setHostname(serviceName);
host.setValid(valid);
return host;
}
public static Host hostInstance(String serviceName, boolean valid, String ip,
int port, Map<String, String> metadata) {
Host host = new Host();
host.setIp(ip);
host.setPort(port);
host.setValid(valid);
host.setHostname(serviceName);
return host;
}
}