LoadBalancer接口
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
/**
* 负载均衡接口
*
* @author wenhui
* @Date 2021/2/21
*/
public interface LoadBalancer {
/**
* 获取需要访问的机器
*
* @param serviceInstances
* @return ServiceInstance
**/
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
MyLB接口实现
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author wenhui
* @Date 2021/2/21
*/
@Component
public class MyLB implements LoadBalancer {
// 使用原子类计数请求的次数
private AtomicInteger atomicInteger = new AtomicInteger(0);
/**
* 获取当前是第几次访问
*
* @return int
**/
public final int getAndIncrement() {
int current;
int next;
// 成功后才会返回期望值,否则无线循环
do {
current = atomicInteger.get();
// 判断当前值是否大于int最大值
next = current >= 2147483647 ? 0 : current + 1;
} while (!this.atomicInteger.compareAndSet(current, next));
System.out.println("访问次数:" + next);
return next;
}
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
// 获取轮询机器下标位置
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
Controller使用
import cn.hutool.json.JSONObject;
import com.wenhui.cloud.lb.MyLB;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author wenhui
* @since 2021-01-23
*/
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class UserController {
private final RestTemplate restTemplate;
private final DiscoveryClient discoveryClient;
private final MyLB myLB;
@GetMapping("/user/payment/mylb")
public JSONObject paymentMyLB() {
List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
if (null == instanceList || instanceList.size() == 0) {
return null;
}
ServiceInstance instance = myLB.instances(instanceList);
URI uri = instance.getUri();
System.out.println("---自定义负载均衡---");
return restTemplate.getForObject(uri + "/api/user/payment/lb", JSONObject.class);
}
}
版权声明:本文为qq_31519989原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。