3

SpringCloud之使用Feign跨服务调用最佳方式

 2 years ago
source link: https://segmentfault.com/a/1190000041283568
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

最近在学习如何使用springcloud,当学习到跨服务调用接口时接触到Feign和Ribbon,网上有好多文章是介绍他们俩的区别的,有兴趣的可以看看,本文主要推荐使用Feign并记录操作过程。

Feign和Ribbon对比

Ribbon
Ribbon 是一个基于 HTTP 和 TCP 客户端的负载均衡器
它可以在客户端配置 ribbonServerList(服务端列表),然后轮询请求以实现均衡负载
它在联合 Eureka 使用时
ribbonServerList 会被 DiscoveryEnabledNIWSServerList 重写,扩展成从 Eureka 注册中心获取服务端列表
同时它也会用 NIWSDiscoveryPing 来取代 IPing,它将职责委托给 Eureka 来确定服务端是否已经启动

Feign
Spring Cloud Netflix 的微服务都是以 HTTP 接口的形式暴露的,所以可以用 Apache 的 HttpClient 或 Spring 的 RestTemplate 去調用
而 Feign 是一個使用起來更加方便的 HTTP 客戶端
总结起来就是:发布到注册中心的服务方接口,是 HTTP 的,也可以不用 Ribbon 或者 Feign,直接浏览器一样能够访问
只不过 Ribbon 或者 Feign 调用起来要方便一些,最重要的是:它俩都支持软负载均衡
注意:spring-cloud-starter-feign 里面已经包含了 spring-cloud-starter-ribbon(Feign 中也使用了 Ribbon)
从实践上看,采用feign的方式更优雅(feign内部也使用了ribbon做负载均衡)。

1、引入feign依赖包

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

2、启用feign:@EnableFeignClients

@SpringBootApplication
// 资源保护服务
@EnableResourceServer
// 服务发现
@EnableDiscoveryClient
// 启用feign
@EnableFeignClients
@RefreshScope
public class NofityServiceApplication {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

3、配置feign传递token

@Configuration
public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
      ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String authorization = request.getHeader("authorization");
        log.info("--- authorization ---:{}", authorization);
        if (authorization != null) {
            log.info(" ---- set authorization ---");
            //添加token
            requestTemplate.header("authorization", authorization);
        }
    }
}

4、使用feign调用其它微服务接口

新建AccountFeignClient.java文件

@FeignClient("account-service")
public interface AccountFeignClient {

    @GetMapping("/userInfo/{userName}")
    User getAccountInfoByUserName(@PathVariable("userName") String userName);
}

这样就完成了feign配置的所有操作,试试调用是不是OK了!

1、feign跨服务调用的时候会有token的传递,所以一定要加上上面的config配置
2、如果被调用的服务接口不需要token,如果你调用的接口传递了token会报401,这个要注意一下!

SpringCloud系列之服务消费Ribbon和Feign区别


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK