🔎这里是【秒懂·云原生】,关注我学习云原生不迷路
👍如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位🔎点赞👍评论收藏⭐️
👀专栏介绍
【秒懂·云原生】 目前主要更新微服务,一起学习一起进步。
👀本期介绍
主要介绍Spring Cloud Commons:公共抽象
文章目录
👀Spring Cloud Commons:公共抽象
Spring Cloud将服务发现、负载均衡和断路器等通用模型封装在一个公共抽象中,可以被所有的Spring Cloud客户端使用,不依赖于具体的实现(例如服务发现就有Eureka和Consul等不同的实现),这些公共抽象位于Spring Cloud Commons项目中。
🪂@EnableDiscoveryClient
🪂服务注册ServiceRegistry
@Configuration
@EnableDiscoveryClient(autoRegister=false)
public class MyConfiguration {
private ServiceRegistry registry;
public MyConfiguration(ServiceRegistry registry) {
this.registry = registry;
}
// called via some external process, such as an event or a custom actuator endpoint
public void register() {
Registration registration = constructRegistration();
this.registry.register(registration);
}
}
每个ServiceRegistry实现都有自己的Registry实现。
🪂RestTemplate的负载均衡
@Configuration
public class MyConfiguration {
@LoadBalanced
@Bean
RestTemplate restTemplate(){
return new RestTemplate():
}
}
public class MyApplication {
@Autowired
private RestTemplate restTemplate ;
public string getMyApplicationName() {
//使用restTemplate访问my-application微服务的/name接口
string name = restTemplate.getFor0bject("http://my-application/name",string.class) ;
return name;
}
}
🪂RestTemplate的失败重试
@Configuration
public class RryListenerConfiguration {
@Bean
LoadBalancedRetryListenerFactory retryListenerFactory( {
return new LoadBalancedRetryListenerFactoryO {
@override
public RetryListener[] createRetryListeners (String service)
return new RetryListener[] {new RetryListener ( {
@Override
//重试开始前的工作
public<T,E extends Throwable> boolean open(RetryContext context,RetryCallback<T,E>callback){
return true;
}
//重试结束后的工作@Override
public<T, E extends Throwable> void close(RetryContext context,RetryCallback<T,E>callback,Throwable throwable){
}
//重试出错后的工作@Override
publicT,E extends Throwable> void onError(RetryContext context,RetryCal1back<T,E>callback,Throwable throwable){
}
}};
}};
}}
其中,自定义配置类中定义了生成LoadBalancedRetryListenerFactory实例的@Bean方法,该工厂类的createRetryListeners方法会生成一个RetryListener实例,用于进行网络请求的重试。