springclould loadbalancer下ribbon.listOfServers替代方案

2023-04-27 15:00:54 浏览数 (2)

一、概述

    springclould2.x时,通过<name>.ribbon.listOfServers配置可以做到当关闭注册中心时使用配置的地址进行rpc调用,此时rpc的组合是ribbon feign hystrix。然后升级springclould到2020或2022时,因为这版剔除了ribbon和hystrix,替换成了loadbalancer,所以<name>.ribbon.listOfServers这个配置失效了。在本地开发时,必须要注册到注册中心,才能完成调用,多人协作时相当不便。

    不过loadbalancer可以进行自定义的负载策略,基于此可变相实现<name>.ribbon.listOfServers的功能。

二、配置

2.1配置类

代码语言:javascript复制
@Configuration
@ConfigurationProperties(prefix = "dev.model")
public class DevModelLocalServerConfig {
	private Map<String, String> servers = new HashMap<>();

	
	public Map<String, String> getServers() {
		return this.servers;
	}

	
	public void setServers(Map<String, String> servers) {
		this.servers = servers;
	}

	
	@Override
	public String toString() {
		return "DevModelLocalServerConfig []";
	}

}

2.2自定义负责均衡策略类

代码语言:javascript复制
public class DevModeltLoadBalancer implements ReactorServiceInstanceLoadBalancer {
	final String serviceId;
	final Map<String, String> devServers;

	ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

	public DevModeltLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
			String serviceId, Map<String, String> devServers) {
		this.serviceId = serviceId;
		this.devServers = devServers;
		this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
	}

	@Override
	public Mono<Response<ServiceInstance>> choose(Request request) {
		ServiceInstanceListSupplier supplier = this.serviceInstanceListSupplierProvider
				.getIfAvailable(NoopServiceInstanceListSupplier::new);
		RetryableRequestContext o = (RetryableRequestContext) request.getContext();
		URI url = o.getClientRequest().getUrl();
		String host = url.getHost();
		return supplier.get(request).next().map(instances -> {
			if (!this.devServers.containsKey(host)) {
				return new EmptyResponse();
			}
			String address = this.devServers.get(host);
			String[] addStrings = address.split(":");
			ServiceInstance instance = new DefaultServiceInstance(host, host, addStrings[0],
					Integer.valueOf(addStrings[1]), false);
			return new DefaultResponse(instance);
		});
	}
}

2.3bean注入

代码语言:javascript复制
@Configuration
@ConditionalOnProperty(name = "spring.profiles.active", havingValue = "dev")
public class DevModelLoadBalanceConfig {
	@Autowired
	private DevModelLocalServerConfig devModelLocalServerConfig;

	@Bean
	ReactorLoadBalancer<ServiceInstance> reactorLoadBalancer(Environment environment,
			LoadBalancerClientFactory loadBalancerClientFactory) {
		String name = environment.getProperty("spring.application.name");
		return new DevModeltLoadBalancer(
				loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name,
				this.devModelLocalServerConfig.getServers());
	}
}

2.4配置文件

代码语言:javascript复制
dev.model.servers.xxx=127.0.0.1:11003

3、说明

    当spring.profiles.active配置为dev生效,其它值继续走注册中心获取服务地址。

0 人点赞