springcloud学习记录-ribbon的负载均衡调用

加入依赖:

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

这个依赖里面已经包含了ribbon:
在这里插入图片描述

然后是application.yml:

server:
  port: 801  #80端口会出问题,且下面配置不写也会出问题。
spring:
  application:
    name: cloud-order-service
  zipkin:
    base-url: http://localhost:9411
    sleuth:
      sampler:  #采样率介于01之间,1表示全部采集
        probability: 1
eureka:
  client:
    #是否让自己注册EurekaServer 默认为true
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息, 默认为true 单节点无所谓,集群必须设置为true,才能配合ribbon负载均衡
    fetchRegistry: true
    service-url:
      #defaultZone: http://localhost:7001/eureka
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群板

定义自己的规则:

@Configuration
public class MySelfRule {
        @Bean
        public IRule myRule(){
            return  new RandomRule();
        }
}

配置类:
去掉@LoadBalanced:

   @Configuration
    public class ApplicationContextConfig {
        @Bean
//        @LoadBalanced  去掉负载均衡的注解
        public RestTemplate getRestTemplate(){
            return new RestTemplate();
        }
    }

定义重写规则的接口:

public interface LoadBalancer {
    ServiceInstance instance(List<ServiceInstance> serviceInstances);
}

重写规则方法:

@Component
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger =new AtomicInteger(0);

    public final int getAndIncrement(){
                int current;
                int next;
                do{
                    current = this.atomicInteger.get();
                    next=current>=2147483647 ? 0 : current+1;
                } while(!this.atomicInteger.compareAndSet(current,next));
        System.out.println("地基持访问next:"+next);
        //相当于内存值是一个锁,current期望值是钥匙,而next是要放进箱子里的东西
        return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {

        int index=  getAndIncrement()%serviceInstances.size();
        //通过取余来得到list的下标
        return serviceInstances.get(index);//通过得到的下标选取服务器集群里的服务器
    }
}

controller层:

@RestController
@Slf4j
public class OrderController {

//    public static final String PAYMENT_URL="http://localhost:8001";
    public static final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){

        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment, CommonResult.class);
    };
    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long  id){
        return  restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }
    @GetMapping(value = "/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getPayment2(@PathVariable("id") Long  id){

         ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

          if(entity.getStatusCode().is2xxSuccessful()){
              return entity.getBody();
          }else {
              return  new CommonResult<>(444,"操作失败");
          }
    }
 @GetMapping(value = "/consumer/payment/lb")
    public  String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
                                          //cloud-payment-service
        if(instances==null||instances.size()<=0){
                return  null;
        }
        ServiceInstance serviceInstance = loadBalancer.instance(instances);
        URI uri = serviceInstance.getUri();
        return  restTemplate.getForObject(uri+"/payment/lb",String.class);
    }
 }

主启动类:

@SpringBootApplication
@EnableEurekaClient
//@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
public class OrderMain801 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain801.class,args);
    }
}

启动7001,7002集群,8001,8002进行微服务改造
最后进行访问:http://localhost/consumer/payment/lb
轮询访问服务器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值