03_远程调用

1. 配置服务注册功能

  • 详情请看上一篇文章

2. pom添加Feign依赖

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

    </dependencies>

3. 编写远程调用接口

// 统一放在feign包下,这样一眼就看出这是远程调用接口
package com.atguigu.gulimall.member.feign;

import com.atguigu.common.utils.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;


// 注解,表明调用注册中心中的哪一个服务
@FeignClient("gulimall-coupon")
public interface CouponFeignService {

    // 具体调用哪一个uri
    @RequestMapping("/coupon/coupon/member/list")
    public R membercoupons();
}

4. 开启远程调用(启动类(配置类)中加注解)


@SpringBootApplication
// 开启远程调用功能,同时指定哪一个包下是远程调用接口
@EnableFeignClients(basePackages = "com.atguigu.gulimall.member.feign")
public class GulimallMemberApplication {

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

}

5. 通过远程调用接口调用远程服务

@RestController
@RequestMapping("member/member")
public class MemberController {

    // 注入远程调用接口
    @Autowired
    CouponFeignService couponFeignService;

    // 在里面调用远程服务
    @RequestMapping("/coupons")
    public R test() {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setNickname("张三");
        R membercoupons = couponFeignService.membercoupons();
        return R.ok().put("member", memberEntity).put("coupons", membercoupons.get("coupons"));


    }

}

6. Feign使用优化

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

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

6.2 优化方法

  • 使用连接池来代替默认的URLConnection

6.3 具体步骤

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值