自学内容网 自学内容网

Spring Cloud Alibaba 03_使用 openFeign 实现远程调用

1. 引入依赖

<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-openfeign</artifactId>  
    <!-- 版本号应该与你的 Spring Cloud 版本兼容 -->  
</dependency>

2. 启用 OpenFeign

配置类添加 @EnableFeignClients 注解以启用 OpenFeign 的自动配置。该注解会告诉 SpringBoot 在启动时扫描并注册所有标记了 @FeignClient 的接口。

@SpringBootApplication  
@EnableFeignClients  
public class Application {  
    public static void main(String[] args) {  
        SpringApplication.run(Application.class, args);  
    }  
}

3. 声明 Feign 客户端

使用 @FeignClient 注解声明一个 Feign 客户端,name 属性指定远程服务的名称。通过该接口定义远程服务的方法。

@FeignClient(name = "remote-service")  
public interface RemoteServiceClient {  
  
    @GetMapping("/api/data")  
    String getData();  
  
    @PostMapping("/api/data")  
    ResponseEntity<String> postData(@RequestBody String data);  
}

4. 使用 Feign 客户端

@Service  
public class MyService {  
  
    @Autowired  
    private RemoteServiceClient remoteServiceClient;  
  
    public void someMethod() {  
        String data = remoteServiceClient.getData();  
        // 处理数据  
    }  
}

5. Ribbon 负载均衡

SpringCloud2020 版本以前的 OpenFeign 默认集成了 Ribbon 作为客户端负载均衡器,其默认的负载均衡策略为轮询,可以通过配置修改负载均衡策略。

修改负载均衡策略为随机的配置示例:

your-service-name:  
  ribbon:  
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

6. Spring Cloud LoadBalancer 负载均衡

SpringCloud2020 版本以后的 OpenFeign 默认集成了 Spring Cloud LoadBalancer,默认负载均衡策略为轮询,内置了轮询、随机等策略,配置随机内置策略的示例如下:

@Configuration  
public class CustomLoadBalancerConfiguration {  
  
    @Bean  
    public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {  
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);  
        return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);  
    }  
}
@SpringBootApplication  
@EnableDiscoveryClient  
@LoadBalancerClients(defaultConfiguration = CustomLoadBalancerConfiguration.class)  
public class MyApplication {  
    public static void main(String[] args) {  
        SpringApplication.run(MyApplication.class, args);  
    }  
}

你也可以通过实现 ReactiveLoadBalancer<ServiceInstance> 接口来实现自定义策略。

import org.springframework.cloud.client.ServiceInstance;  
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;  
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;  
import reactor.core.publisher.Flux;  
  
import java.util.List;  
  
public class RandomLoadBalancer implements ReactorLoadBalancer<ServiceInstance> {  
  
    private final ServiceInstanceListSupplier serviceInstanceListSupplier;  
  
    public RandomLoadBalancer(ServiceInstanceListSupplier serviceInstanceListSupplier) {  
        this.serviceInstanceListSupplier = serviceInstanceListSupplier;  
    }  
  
    @Override  
    public Mono<Response<ServiceInstance>> choose(Request request) {  
        return serviceInstanceListSupplier.get()  
                .map(serviceInstances -> {  
                    if (serviceInstances.isEmpty()) {  
                        return new EmptyResponse();  
                    }  
                    List<ServiceInstance> instances = serviceInstances.get();  
                    // 这里简单地通过随机索引来选择服务实例  
                    int index = (int) (Math.random() * instances.size());  
                    return new DefaultResponse(instances.get(index));  
                })  
                .single();  
    }  
}
@Configuration  
public class LoadBalancerConfig {  
  
    @Bean  
    public ReactorLoadBalancer<ServiceInstance> customLoadBalancer(Environment environment,  
                                                                   LoadBalancerClientFactory loadBalancerClientFactory) {  
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);  
        return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class));  
    }  
}

原文地址:https://blog.csdn.net/BLU_111/article/details/142443496

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!