package cn.reghao.tnb.content.app.mall.feign;

//import com.netflix.loadbalancer.IRule;
//import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

/**
 * @author reghao
 * @date 2025-07-23 15:40:24
 */
@LoadBalancerClient(name = "user-service", configuration = LoadBalanceConfig.CustomLoadBalancerConfiguration.class)
@Configuration
public class LoadBalanceConfig {
    /*@Bean
    public IRule iRule() {
        return new RoundRobinRule();
    }*/

    @Bean(name = "lbRestTemplate")
    // 提供客户端负载均衡
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    static class CustomLoadBalancerConfiguration {
        @Bean
        ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                                LoadBalancerClientFactory loadBalancerClientFactory) {
            String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
            // 随机负载均衡策略
            RandomLoadBalancer randomLoadBalancer = new RandomLoadBalancer(
                    loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
            // 轮询负载均衡策略
            RoundRobinLoadBalancer roundRobinLoadBalancer = new RoundRobinLoadBalancer(
                    loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
            return roundRobinLoadBalancer;
        }
    }
}
