RestTemplate与Feign

1.6 远程调用

服务远程调用(Service Remote Invocation)是指在分布式系统中,通过网络将一个应用程序运行的服务(Service)请求发送到远程计算机上的另一个应用程序中执行。通常情况下,服务远程调用是通过网络传输协议(如HTTP、TCP/IP等)来实现的,而且通常使用特定的中间件或框架进行管理。

常见技术有:RestTemplatefeign远程调用

Feign是一个基于Java的声明式HTTP客户端,用于简化服务间的通信。Feign可以与EurekaRibbon等服务发现和负载均衡框架集成,可以通过注解方式声明服务接口,并自动实现远程服务的调用。

1.6.1 RestTemplate基本使用

RestTemplate是一个Spring提供的HTTP客户端工具,用于发送HTTP请求和接收响应,基本使用如下

  1. 导依赖,Spring自带的,所以只要是Spring项目就能用
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 创建一个RestService类,用于向外部服务发送HTTP请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestService {

    @Autowired  //自动装配
    private RestTemplate restTemplate;

    public String getResponse(String url) {
        //发起get请求,返回对象为String类型(自动将JSON格式序列化为对象)
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        return response.getBody();
    }
}
  1. 在应用程序主类中创建RestTemplate实例,2步骤时已经将其注入到RestService中了
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class Application {

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

    @Bean
    //@LoadBalanced 基于Eureka实现负载均衡,feign不用基于其他技术就能负载均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  1. 在控制器类中使用RestService类发送HTTP请求:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    private RestService restService;

    @GetMapping("/test")
    public String test() {
        String response = restService.getResponse("https://www.csdn.net/");
        return response;
    }
}
  1. 使用postman测试,成功
1.6.2 feign基本使用

官网:https://github.com/OpenFeign/feign

Spring官方参考文档:https://cloud.spring.io/spring-cloud-openfeign/reference/html/

  • 逻辑梳理:两个服务,feign 8080端口 作为服务消费者 ;user 8888端口 服务提供者,在feign中调用user中提供的接口

基本使用:

  1. pom导包 发起调用的一方,服务消费者
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
   <version>3.1.2</version>
</dependency>
  1. 添加注解
@EnableFeignClients  //开启feign功能
@SpringBootApplication
public class FeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }
}
  1. 编写Feign的客户端,内容如下:
package cn.zhaoxi.feign.client;

import cn.itcast.order.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

//服务名称,所以要配合注册中心用,如果没用注册中心就要写称http://localhost:8080的形式
@FeignClient("userservice")
public interface UserClient {
    @GetMapping("/user/{id}") //请求方式及路径
    User findById(@PathVariable("id") Long id); //请求参数,返回值类型
}
1.6.2.1 feign自定义配置

Feign的自定义配置,如下:

类型作用说明
feign.Logger.Level修改日志级别包含四种不同的级别:NONE、BASIC、HEADERS、FULL
feign.codec.Decoder响应结果的解析器http远程调用的结果做解析,例如解析json字符串为java对象
feign.codec.Encoder请求参数编码将请求参数编码,便于通过http请求发送
feign. Contract支持的注解格式默认是SpringMVC的注解
feign. Retryer失败重试机制请求失败的重试机制,默认是没有,不过会使用Ribbon的重试

一般情况下,默认值就能满足我们使用,如果要自定义时,只需要创建自定义的@Bean覆盖默认Bean即可。

  1. 配置文件方式

基于配置文件修改feign的日志级别可以针对单个服务:

feign:  
  client:
    config: 
      userservice: # 针对某个微服务的配置
        loggerLevel: FULL #  日志级别 

也可以针对所有服务:

feign:  
  client:
    config: 
      default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置
        loggerLevel: FULL #  日志级别 

而日志的级别分为四种:

  • NONE:不记录任何日志信息,这是默认值。
  • BASIC:仅记录请求的方法,URL以及响应状态码和执行时间
  • HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息
  • FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据。
  1. 定义Bean的方式
public class DefaultFeignConfiguration  {
    @Bean
    public Logger.Level feignLogLevel(){
        return Logger.Level.BASIC; // 日志级别为BASIC
    }
}

如果要全局生效,需要将这个类放到启动类的@EnableFeignClients这个注解中:

@EnableFeignClients(defaultConfiguration = DefaultFeignConfiguration .class) 

如果是局部生效,则把它放到对应的@FeignClient这个注解中:

@FeignClient(value = "userservice", configuration = DefaultFeignConfiguration .class) 
1.6.2.2 Feign使用优化

Feign底层发起http请求,依赖于其它的框架。其底层客户端实现包括:

•URLConnection:默认实现,不支持连接池

•Apache HttpClient :支持连接池

•OKHttp:支持连接池

因此提高Feign的性能主要手段就是使用连接池代替默认的URLConnection。如下我们用Apache的HttpClient来演示。

  1. 引入依赖

在对应服务的pom文件中引入Apache的HttpClient依赖:

<!--httpClient的依赖 -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>
  1. 在application.yml中添加连接池配置:
feign:
  client:
    config:
      default: # default全局的配置
        loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息
  httpclient: #连接池
    enabled: true # 开启feign对HttpClient的支持
    max-connections: 200 # 最大的连接数
    max-connections-per-route: 50 # 每个路径的最大连接数
1.6.2.3 最佳解决方案

因为Feign的客户端(服务消费者中)与服务提供者的controller代码非常相似:

feign客户端:

@FeignClient("userservice")
public interface UserClient {
    @GetMapping("/user/{id}")
    User findById(@PathVariable("id") Long id);
}

UserController:

@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id){
    return UserService.getById(id);
}

所以提出了以下优化方案:

  1. 继承方式
  • 定义一个API接口,利用定义方法,并基于SpringMVC注解做声明。
  • Feign客户端和Controller都集成改接口

接口参数注解无法被继承,此方法不推荐,不做过多实例

  1. 设为依赖

将Feign的Client抽取为独立模块,并且把接口有关的POJO、默认的Feign配置都放到这个模块中,提供给所有消费者使用

实现步骤:

  • 首先创建一个module,命名为feign-api(简单的Maven工程)

  • 在feign-api中然后引入feign的starter依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 编写对应的UserClient、User、DefaultFeignConfiguration文件

  • 在其他服务(模块)中使用feign-api只需要在pom文件中引入feign-api这个依赖:

<dependency>
    <groupId>cn.itcast.demo</groupId>
    <artifactId>feign-api</artifactId>
    <version>1.0</version>
</dependency>
  • 重启测试会报 could not be found 的错误

这是因为UserClient与@EnableFeignClients注解不在同一个包,所以无法扫描到UserClient。

方式一:指定Feign应该扫描的包:(包下的所有文件)

@EnableFeignClients(basePackages = "com.zhaoxi.feign.clients")

方式二:指定需要加载的Client接口:(只有指定的这个类,所以开销更小)

@EnableFeignClients(clients = {UserClient.class})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值