spring-cloud-starter-loadbalancer 使用

1:pom.xl

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    <version>3.0.3</version>
</dependency>

2.FeignLoadBalancerConfig

/**
 * 是有缓存的,默认是35s,如修改缓存时间,可做如下配置
 * spring.cloud.loadbalancer.cache.ttl=5s
 */
@ConditionalOnDiscoveryEnabled
public class FeignLoadBalancerConfig {

    @Bean
    @ConditionalOnMissingBean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(Environment environment,
            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new HashLoadBalancer(
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }



}

3.FeignConfig

public class FeignConfig {
    @Bean
    public Retryer getRetryBean() {
        return Retryer.NEVER_RETRY;
        // return new Retryer.Default();// 可将服务端设置超时,可看到多次进入服务端请求
    }

}

4.HashLoadBalancer

@Slf4j
public class HashLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private final String serviceId;

    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    private final AtomicInteger position;

    public HashLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) {
        this(serviceInstanceListSupplierProvider, serviceId, new Random().nextInt(1000));
    }

    public HashLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId, int seedPosition) {
        this.serviceId = serviceId;
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
        this.position = new AtomicInteger(seedPosition);
    }


    @SuppressWarnings("rawtypes")
    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider
                .getIfAvailable(NoopServiceInstanceListSupplier::new);
        return supplier.get(request).next()
                       .map(serviceInstances -> processInstanceResponse(request, supplier, serviceInstances));
    }

    private Response<ServiceInstance> processInstanceResponse(Request request, ServiceInstanceListSupplier supplier,
            List<ServiceInstance> serviceInstances) {
        Response<ServiceInstance> serviceInstanceResponse = getInstanceResponse(request, serviceInstances);
        if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) {
            ((SelectedInstanceCallback) supplier).selectedServiceInstance(serviceInstanceResponse.getServer());
        }
        return serviceInstanceResponse;
    }

    private Response<ServiceInstance> getInstanceResponse(Request request, List<ServiceInstance> instances) {
        if (instances.isEmpty()) {
            if (log.isWarnEnabled()) {
                log.warn("No servers available for service: " + serviceId);
            }
            return new EmptyResponse();
        }

        // 节点实例
        if (null != request.getContext() && request.getContext() instanceof RequestDataContext) {
            // 获取请求头sharding属性值
            List<String> sharingIds = ((RequestDataContext) request.getContext()).getClientRequest().getHeaders().get(ClientConstant.sharingId);
            String shardingId = Optional.ofNullable(sharingIds).map(m -> m.get(0)).orElse(null);
            if (null != shardingId) {
                if (log.isDebugEnabled()) {
                    log.debug("getInstanceResponse shardingId = {} instances = {}", shardingId, instances.stream().map(e -> e.getInstanceId()).collect(Collectors.toList()));//todo
                }
                return new DefaultResponse(instances.get(HashKeyUtil.getIndex(shardingId, instances.size())));
            }
        }
        // instance为空说明未配置sharingId,走默认路由规则
        int pos = this.position.incrementAndGet() & Integer.MAX_VALUE;
        return new DefaultResponse(instances.get(pos % instances.size()));
    }

}

5:HashKeyUtil

public class HashKeyUtil {

    //@Autowired
    //private DiscoveryClient discoveryClient;
    // discoveryClient.getInstances("service-name"); 获取在线服务

    public static int getIndex(String key, int serviceSize) {
        return 0 == serviceSize ? 0 : hashLh(key) % serviceSize;
    }

    public static int hashLh(String key) { // 耗时和均布,相对适中
        int h;
        int hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        return hash & Integer.MAX_VALUE;
    }

    public static int hashLong(String key) {
        return (int) (Long.parseLong(key) / 10);
    }

    public static int hashOnly(String key) {
        return key.hashCode() & Integer.MAX_VALUE;
    }
}

6:DemoClient

@FeignClient(name = ExchangeCoreClientConstants.SERVICE_NAME, path = "/inner/exchange/core/asset", configuration = FeignConfig.class)
@LoadBalancerClient(value = ExchangeCoreClientConstants.SERVICE_NAME, configuration = FeignLoadBalancerConfig.class)
public interface DemoClient {

    @PostMapping(value = "/transfer-in")
    ResponseResult transferIn(@RequestBody RequestCommon<TransferTraceAccountInDTO> toDto, @RequestHeader(ClientConstant.sharingId) long sharingId);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring Cloud LoadBalancerSpring Cloud 中的一个组件,用于提供负载均衡功能,可以帮助开发者在微服务架构中轻松地实现服务发现和负载均衡。 Spring Cloud LoadBalancer 提供了一套简单的 API 接口,允许开发者自定义负载均衡策略,并且支持多种负载均衡算法,例如轮询、随机等。它与 Spring Cloud 的服务注册与发现组件集成得很好,能够自动地将服务实例注册到负载均衡器中,并根据需要对服务实例进行负载均衡。 使用 Spring Cloud LoadBalancer 的好处是它可以帮助开发者快速实现服务发现和负载均衡功能,而无需手动编写繁琐的负载均衡算法和服务发现代码。此外,Spring Cloud LoadBalancer 还具有高度可扩展性和灵活性,可以与不同的负载均衡器集成,并且支持自定义的负载均衡算法。 总之,如果您正在使用 Spring Cloud 构建微服务架构,那么使用 Spring Cloud LoadBalancer 可以帮助您更轻松地实现服务发现和负载均衡功能,并且可以提高系统的可扩展性和灵活性。 ### 回答2: Spring Cloud LoadbalancerSpring Cloud提供的一个负载均衡器,用于在微服务架构中实现服务的负载均衡。以下是使用Spring Cloud Loadbalancer的步骤: 1. 引入依赖:在项目的pom.xml文件中添加Spring Cloud Loadbalancer的依赖。 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> ``` 2. 创建服务调用类:首先,我们需要创建一个ServiceInstanceListSupplier的实现,以提供要进行负载均衡的服务实例列表。 ```java import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.ServiceInstanceListSupplier; public class CustomServiceInstanceListSupplier implements ServiceInstanceListSupplier { // 实现ServiceInstanceListSupplier接口的方法 // 返回要进行负载均衡的服务实例列表 } ``` 3. 注册服务调用类:将自定义的ServiceInstanceListSupplier注册到Spring容器。 ```java @Configuration public class LoadBalancerConfig { @Bean public ServiceInstanceListSupplier serviceInstanceListSupplier() { return new CustomServiceInstanceListSupplier(); } } ``` 4. 使用负载均衡器:在需要进行服务调用的地方,可以使用@LoadBalanced注解将RestTemplate、WebClient等进行负载均衡代理。 ```java @Autowired @LoadBalanced private RestTemplate restTemplate; // 在需要进行服务调用的地方,可以直接使用RestTemplate进行调用 ResponseEntity<String> response = restTemplate.getForEntity("http://service-provider/api/endpoint", String.class); ``` 5. 配置负载均衡策略:可以通过配置文件(application.yml或application.properties)来配置负载均衡器的策略。 ```yaml spring: cloud: loadbalancer: ribbon: enabled: false # 禁用默认的Ribbon负载均衡器 ``` 通过以上步骤,我们可以在Spring Cloud项目中使用Spring Cloud Loadbalancer来实现服务的负载均衡。 ### 回答3: spring-cloud-loadbalancerSpring Cloud提供的一个负载均衡器,用于在微服务架构中实现服务的负载均衡。我们可以通过以下步骤来使用spring-cloud-loadbalancer: 1. 在pom.xml文件中,添加spring-cloud-loadbalancer的依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> ``` 2. 创建一个自定义的负载均衡器配置类,实现LoadBalancerClient接口,并注入LoadBalancerProperties对象: ```java @Configuration public class MyLoadBalancerConfig { @Autowired private LoadBalancerProperties loadBalancerProperties; @Bean public LoadBalancerClient loadBalancerClient() { return new LoadBalancerClient() { // 实现接口方法,使用具体的负载均衡算法进行服务的选择 @Override public ServiceInstance choose(String serviceId) { // 在这里选择一个可用的服务实例并返回 } }; } } ``` 3. 创建一个服务消费者类,通过@LoadBalanced注解启用负载均衡能力: ```java @Service public class ConsumerService { @Autowired @LoadBalanced private RestTemplate restTemplate; public void consumeService() { // 发起对服务提供者的请求 ResponseEntity<String> response = restTemplate.getForEntity("http://service-provider/service", String.class); String result = response.getBody(); // 处理返回结果 } } ``` 4. 在应用启动类上添加@EnableDiscoveryClient注解,开启服务注册和发现的能力。 5. 在服务提供者的配置文件中,设置应用的名称和端口号。 6. 运行服务提供者和服务消费者,观察服务消费者通过负载均衡器调用服务提供者的效果。 总结起来,使用spring-cloud-loadbalancer,首先需要添加依赖,然后实现一个自定义的负载均衡器配置类,再在服务消费者中注入负载均衡的RestTemplate,并通过@LoadBalanced注解启用负载均衡能力。最后,通过@EnableDiscoveryClient注解开启服务注册和发现的能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值