4.Cloud-Ribbon+OpenFeign

https://github.com/spring-cloud/spring-cloud-openfeign

1.Ribbon

  1.1官网资料

https://github.com/Netflix/ribbon/wiki/Getting-Started

  1.2.POM

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

  1.3.配置

@Configuration
public class ApplicationContextConfig {
    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
}

  1.4 业务代码

@RequestMapping("consumer/payment")
@RestController
@Slf4j
public class OrderController {

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

    @LoadBalanced
    @Resource
    private RestTemplate restTemplate;

    @GetMapping("create")
    public CommonResult<Payment>   create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment, CommonResult.class);  //写操作
    } 
}

 2.Ribbon核心组件IRule

  2.1 IRule:

        根据特定算法从服务列表中选取一个要访问的服务

  1. com.netflix.loadbalancer.RoundRobinRule
  2. com.netflix.loadbalancer.RandomRule
  3. com.netflix.loadbalancer.RetryRule
  4. WeightedResponseTimeRule
  5. BestAvailableRule
  6. AvailabilityFilteringRule
  7. ZoneAvoidanceRule

  2.2 如何替换

    1) 创建自定义规则

@Configuration
public class MySelfRule {

    @Bean
    public IRule myRule()
    {
        return new RandomRule(); //随机
    } 
}

    2) 主启动类添加@RibbonClient

@EnableEurekaClient
@SpringBootApplication
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = My-SelfRule.class)
public class OrderMain80 {

    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }
}

3 Ribbon负载均衡算法

  1) ApplicationContextBean去掉@LoadBalanced

@Configuration
public class ApplicationContextConfig {
    @Bean
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    }
}

  2) LoadBalancer接口

public interface LoadBalancer {

    //收集服务器总共有多少台能够提供服务的机器,并放到list里面
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

@Component
public class MyLB implements LoadBalancer {
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    //坐标
    private 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);
        return next;
    }
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {  //得到机器的列表
        int index = getAndIncrement() % serviceInstances.size(); //得到服务器的下标位置
        return serviceInstances.get(index);
    }
}

4.OpenFeign

  4.1 概述

https://github.com/spring-cloud/spring-cloud-openfeign

  4.2 POM

<!--Openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

  4.3 YML

server:
  port: 8002

spring:
  application:
    name: cloud-order-service
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.2.18:8848
    inetutils:
      ignored-interfaces: ['VMware.*']

  4.4 主启动类

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

  4.5 业务类

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface  PaymentFeignService {

    @GetMapping(value = "/payment/get/{id}")
    CommonResult index(@PathVariable("id") Long id);

}

  4.6 超时

feign:
  client:
    config:
      default:
        #建立连接所用的时间,适用于网络状况正常的情况下,两端连接所需要的时间
        connect-timeout: : 6000
        #指建立连接后从服务端读取到可用资源所用的时间
        read-timeout: : 10000

  4.7 日志打印功能

    1. 日志级别

        1) NONE:默认,不显示日志

        2) BASIC:仅记录请求方法

        3) HEADERS

        4) FULL

    2. 配置日志bean

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

    3.YML

logging:
  level:
    com.example.cloud.config.FeignConfig: debug

    4.8 

5.consul使用步骤

  1.1 pom

<!--openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
 
<!--consul-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>

  1.2 yml

server:
  port: 80

spring:
  application:
    name: cloud-order-service
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

  1.3 业务类

    cloud-payment:consul服务名

@Service
@FeignClient(value = "cloud-payment")
public interface PaymentFeignService {

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id);

}

  1.4 控制器

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        return paymentFeignService.getPaymentById(id);
    }

}

  1.5 主程序

@EnableFeignClients
@SpringBootApplication
public class OrderOpenFeignMain {

    public static void main(String[] args) {
        SpringApplication.run(OrderOpenFeignMain.class, args);
    }
}

  1.5 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wang_peng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值