DiscoveryClient和Ribbon

2018-09-05  本文已影响0人  莫看烟雨

@EnableDiscoveryClient

@Autowired
private DiscoveryClient discoveryClient;

public Object getResult(String api) {
RestTemplate restTemplate = new RestTemplate();
List<ServiceInstance> instances =
discoveryClient.getInstances("serviceName");
if (instances.size()==0) return null;
String serviceUri = String.format("%s/%s",
instances.get(0).getUri().toString(),
api);
ResponseEntity< Object > restExchange =
restTemplate.exchange(
serviceUri,
HttpMethod.GET,
null, Object.class);
return restExchange.getBody();
}

DiscoveryClient会返回所有的可用服务方,由你自主选择使用哪一个进行调用。

@LoadBalanced && Ribbon

 /**
 * Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient
 * @author Spencer Gibb
 */
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface LoadBalanced {
}

/**
 * This annotation may be used on a field or parameter as a qualifier for
 * candidate beans when autowiring. It may also be used to annotate other
 * custom annotations that can then in turn be used as qualifiers.
 *
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @since 2.5
 * @see Autowired
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Qualifier {

    String value() default "";

}
上一篇 下一篇

猜你喜欢

热点阅读