标签:while scope compare 访问 工作 payment 订单 其他 object
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> <version>2.2.1.RELEASE</version> <scope>compile</scope> </dependency>
@Configuration public class MySelfRule { @Bean public IRule myRule() { //将负载均衡策略改为随机 return new RandomRule(); } }
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class) @EnableEurekaClient @SpringBootApplication public class OrderMain80 { public static void main(String[] args) { SpringApplication.run(OrderMain80.class, args); } }
@GetMapping("/payment/lb") public String getPaymentLB() { return serverPort; }
public interface LoadBalancer { ServiceInstance instances(List<ServiceInstance> serviceInstances); }
@Component public class MyLB implements LoadBalancer { private AtomicInteger atomicInteger = new AtomicInteger(0); public final int getAndIncrement() { int current; int next; do { current = this.atomicInteger.get(); next = current >= 2147483000 ? 0 : current+1; } while(!this.atomicInteger.compareAndSet(current, next)); return next; } @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { int index = getAndIncrement() % serviceInstances.size(); return serviceInstances.get(index); } }
@Resource private RestTemplate restTemplate; @Resource private LoadBalancer loadBalancer; @Resource private DiscoveryClient discoveryClient; @GetMapping("/consumer/payment/lb") public String getPaymentLB() { List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"); if(instances == null || instances.size() <= 0) { return null; } ServiceInstance serviceInstance = loadBalancer.instances(instances); URI uri = serviceInstance.getUri(); return restTemplate.getForObject(uri+"/payment/lb", String.class); }
标签:while scope compare 访问 工作 payment 订单 其他 object
原文地址:https://www.cnblogs.com/binwenhome/p/13189113.html