SpringCloud03_服务调用(Ribbon+RestTemplate、OpenFeign)

1、Ribbon+RestTemplate

  • 服务调用与负载均衡
1.1 Ribbon

Ribbon主要功能是提供客户端软件负载均衡算法和服务调用,属于进程内LB(负载均衡+restTemplate调用)。
负载均衡(LB)分为集中式和进程内,就是将用户请求平均分摊到多个服务器,从而达到系统高可用。

  • 依赖:spring-cloud-starter-netflix-eureka-client集成引入了ribbon
       <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

在这里插入图片描述
例子:
在这里插入图片描述

1.2 RestTemplate

在这里插入图片描述

@Configuration
public class ApplicationConfig {
    @Bean
    @LoadBalanced //开启负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

(1)常见方法

  • getForObject/getForEntity
  • postForObject/postForEntity
  • GET请求方法
  • POST请求方法
public class PaymentController {

//    public static final String payment_URL ="http://localhost:8001";
    public static final String payment_URL ="http://PAYMENT";

    private final RestTemplate restTemplate  ;

    @GetMapping("/get/save")
    public Result<Payment> saveEntity(Payment payment) {
        return restTemplate.postForObject(payment_URL+"/payment/save",payment,Result.class);
    }

    @GetMapping("/{id}")
    public Result getEntity(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(payment_URL+"/payment/"+id,Result.class);
    }

    @GetMapping("/entity/{id}")
    public Result getForEntity(@PathVariable("id") Integer id) {
        ResponseEntity<Result> resultResponseEntity = restTemplate.getForEntity(payment_URL+"/payment/"+id,Result.class);
        if(resultResponseEntity.getStatusCode().is2xxSuccessful()){
            return  resultResponseEntity.getBody();
        } else {
            return  new Result(404,"失败","");
        }
    }
}
1.3 Ribbon默认负载规则(IRule)

1.3.1 使用
Ribbon组件IRule有7种负载均衡规则实现,默认使用的是轮询;
在这里插入图片描述
如果要更改默认规则,自定义配置类不能放在@ComponentScan所扫描的当前包以及子包下面(主启动类扫描范围内),否则就会被所有Ribbion客户端共享,无法实现定制化。

在这里插入图片描述
配置类:MySelfRule.java

@Configuration
public class MySelfRule {
    @Bean
    public IRule iRule(){
        return new RandomRule();//定义为随机
    }
}

主启动类:添加扫描注解,value为注册的服务名,configuration为配置类名.class

@SpringBootApplication(scanBasePackages = "com.consumer")
@EnableEurekaClient
@RibbonClient(value = "PAYMENT",configuration = MySelfRule.class)
public class ConsumerApplication {

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

1.3.2 原理

  • 轮询原理:
    rest请求次数%服务器集群数 = 调用服务器下标(重启服务请求次数从1开始计算)
    1%2 = 1 ,调用 list.get(1);
    2%2 = 0 ,调用 list.get(0);

2、OpenFeign

服务接口调用。
(1)基本概念

  • Feign是一个声明式的WebService客户端,使用方法是定义一个服务接口然后添加注解。
  • Feign是对微服务客户端的进一步封装,Feign集成了ribbion。
  • OpenFeign在OpenFeign的基础上支持springmvc注解,并通过代理的方式产生实现类,实现类中做负载均衡并调用服务。

(2)OpenFeign的使用

  • pom.xml
      <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
  • application.yml 不注册进注册中心:register-with-eureka: false
server:
  port: 8085

eureka:
  client:
    register-with-eureka: false #是否要注册
    fetchRegistry: true #是否抓取注册信息
    service-url:
      #      defaultZone: http://localhost:7001/eureka
      defaultZone: http://eureka7001:7001/eureka,http://eureka7002:7002/eureka

spring:
  application:
    name : consumer8085

  datasource:
    url: jdbc:mysql://localhost:3306/springboot-mybatisplus?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    username: root
    password: 123456
    driver-class-name=com: mysql.cj.jdbc.Driver

#2、mybatis-plus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config :
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
  mapper-locations: classpath:mapper/*.xml

  • 主启动类:@EnableFeignClients 激活
@SpringBootApplication(scanBasePackages = "com.payment")
@EnableFeignClients //激活
public class Payment7Application {

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

}
  • 业务实现
    在这里插入图片描述
    PaymentFeignService.java

——@FeignClient(value = “PAYMENT”)
——@Component

@FeignClient(value = "PAYMENT") //值为注册的支付模块微服务application.name
@Component
public interface PaymentFeignService {

    @GetMapping("/payment/{id}") //对应支付模块该接口的地址
    public Result<Payment> getEntity(@PathVariable("id") Integer id);
}

PaymentController .java

采坑7:@Resource注解注入

@RestController
@RequestMapping("/consumer4")
public class PaymentController {

    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping("/payment/{id}")//diao
    public Result getById (@PathVariable("id") Integer id){
        return paymentFeignService.getEntity(id);
    }
}

访问:http://localhost:8085/consumer4/payment/1
在这里插入图片描述

(3)其他操作
  • 超时控制:默认连接时间超过1秒返回超时异常,可以通过application.yml设置超时时间。
ribbon:
  ReadTimeOut: 5000 #请求连接时间
  ConnectT888imeout: 5000 #资源处理时间
  • 日志增强
    提供5中日志等级
    ——配置类
    在这里插入图片描述
@Configuration
public class FenConfig {
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

——配置开启
在这里插入图片描述

logging:
  level:
     com.payment.FeignService: debug
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值