当前位置 主页 > 服务器问题 > Linux/apache问题 >
获取所有注册的服务,从注册的服务中选取一个,服务调用
package com.xyz.comsumer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class HelloController { @Autowired private LoadBalancerClient loadBalancer; @Autowired private DiscoveryClient discoveryClient; private String serviceName = "service-provider"; @RequestMapping("/services") public Object services() { return discoveryClient.getInstances(serviceName); } @RequestMapping("/discover") public Object discover() { return loadBalancer.choose(serviceName).getUri().toString(); } @RequestMapping("/hello") public String hello() { ServiceInstance serviceInstance = loadBalancer.choose(serviceName); String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class); return callServiceResult; } }
注:
客户端调用的服务名,是在服务端指定的,在服务端配置里使用 spring.cloud.consul.discovery.service-name指注册到 Consul 的服务名称
测试
启动Consul
启动provider和provider1
启动comsumer
测试地址 http://localhost:8015/services
返回结果
[ { "instanceId": "provider-8010", "serviceId": "service-provider", "host": "hkgi-PC", "port": 8010, "secure": false, "metadata": { "secure": "false" }, "uri": "http://hkgi-PC:8010", "scheme": null }, { "instanceId": "provider-8011", "serviceId": "service-provider", "host": "hkgi-PC", "port": 8011, "secure": false, "metadata": { "secure": "false" }, "uri": "http://hkgi-PC:8011", "scheme": null } ]
测试地址 http://localhost:8015/discover
返回结果
http://hkgi-PC:8011 或 http://hkgi-PC:8011 测试地址 http://localhost:8015/hello 返回结果 hello,provider 或 hello,another provider注:
结果交替出现的,这是因为负载均衡器是采用的是轮询的方式
说明:
调用的过程:
A.通过LoadBalancerClient查询服务
B.通过RestTemplate调用远程服务
Ribbon负载均衡策略
BestAvailableRule AvailabilityFilteringRule WeightedResponseTimeRule RetryRule RoundRobinRule RandomRule ZoneAvoidanceRule自定义Ribbon负载均衡——使用随机访问策略
修改启动类
package com.xyz.comsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class ComsumerApplication { public static void main(String[] args) { SpringApplication.run(ComsumerApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }