springcloud学习笔记-Feign

上篇文章介绍了springcloud中eureka以及ribbon的基本使用方式,本文继续记录feign的学习历程

什么是feign

feign与ribbon一样,作用都是在springcloud中调用服务的。feign底层也是ribbon,对ribbon进行了再次封装。

feign与ribbon的使用方式区分

  • .ribbon通过注入restTemplate来实现对服务的调用,在调用时需要手动构建http请求
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
        log.info("consumer启动成功");
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate()
    {
        return new RestTemplate();
    }
}
    @Autowired
    RestTemplate restTemplate;

    @Override
    public String hiService(String name) throws UnknownHostException {
        //当前机器ip
        InetAddress ia = InetAddress.getLocalHost();
       //构建http请求
        for (int i =0;i<1;i++){
            String str = restTemplate.getForObject("http://SERVICE-HI/hi?name=" + name, String.class);
            log.info( str + " 第 " + i + " 次调用");
        }
        return "0";
    }
  • feign通过指定FeignClient,通过接口直接调用服务
@FeignClient("SERVICE-HI")
public interface DemoServiceFeign {

    /**
     *  注意:
     *      @RequestParam 中 value要与服务提供方接口中声明的参数一致
     *      @PostMapping 中 url要与服务提供方url一致
     * @param name
     * @return
     */
    @PostMapping("/hi")
    String hello(@RequestParam(value = "name") String name);
}

feign调用服务

    @Autowired
    private DemoServiceFeign demoServiceFeign;

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam String name) throws UnknownHostException {
        return demoServiceFeign.hello(name);
    }

feign依赖

  • 不同版本的springcloud,对应的feign依赖也不同,文中使用这个maven坐标
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
  • 老版本坐标,如果版本不符合,maven会显示spring-cloud-starter-feign:unknow
      
            org.springframework.cloud
            spring-cloud-starter-feign
        

使用feign

  • 引入feign,启动类添加@EnableFeignClients注解,
    详情见官网 https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.0.RC1/reference/html/#netflix-feign-starter
    中文文档 https://www.springcloud.cc/spring-cloud-dalston.html#spring-cloud-feign
@Slf4j
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
//@EnableHystrix
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
        log.info("consumer启动成功");
    }


}
  • 编写接口,接口添加@FeignClient注解
@FeignClient("SERVICE-HI")
public interface DemoServiceFeign {

    /**
     *  注意:
     *      @RequestParam 中 value要与服务提供方接口中声明的参数一致
     *      @PostMapping 中 url要与服务提供方url一致
     * @param name
     * @return
     */
    @PostMapping("/hi")
    String hello(@RequestParam(value = "name") String name);
}

官网中有说明,FeignClient注解中需要加入被feign调用服务的 应用名称:spring.application.name=service-hi;文档还提到“您还可以使用url属性(绝对值或只是主机名)指定URL”,本文使用服务名称

  • 控制层调用,注入接口调用,当做普通方法调用即可
    注意这里不需要在注入restTemplate类来手动构建http请求了。
    feign底层的介绍推荐这几篇文章:https://blog.csdn.net/qq_39470742/article/details/83539517
    博主有很多篇介绍feign源码的文章
    @Autowired
    private DemoServiceFeign demoServiceFeign;

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam String name) throws UnknownHostException {
        return demoServiceFeign.hello(name);
    }
  • 调用结果,已经使用feign实现了服务间调用


    图片.png
  • feign切换负载均衡策略
    文章开头有说道feign本质上调用的也是ribbon,是对ribbon的高度封装,因此切换负载均衡策略,实际上就是对ribbon切换负载均衡策略

SERVICE-HI:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

ribbon默认轮询策略,这里切换为随机策略,可以看到结果已经成功了

图片.png

到这里feign简单使用已经完成了,至于服务间调用选择feign还是ribbon,网上有很多种说法,个人感觉feign确实很好用,接口以及注解标明调用的api可读性很强,更容易上手。下面介绍一些使用feign时遇到的问题

read time out

feign底层使用的ribbon,ribbon本身有默认的超时时间,在LoadBalancerFeignClient.java类中有execute方法,如下:

        @Override
    public Response execute(Request request, Request.Options options) throws IOException {

execute方法中有两个参数,Request是包含一些请求信息,Options是配置相关信息,Options类内容如下:

public static class Options {
        private final int connectTimeoutMillis;
        private final int readTimeoutMillis;
        private final boolean followRedirects;

        public Options(int connectTimeoutMillis, int readTimeoutMillis, boolean followRedirects) {
            this.connectTimeoutMillis = connectTimeoutMillis;
            this.readTimeoutMillis = readTimeoutMillis;
            this.followRedirects = followRedirects;
        }

        public Options(int connectTimeoutMillis, int readTimeoutMillis) {
            this(connectTimeoutMillis, readTimeoutMillis, true);
        }

        public Options() {
            this(10000, '\uea60');
        }

        public int connectTimeoutMillis() {
            return this.connectTimeoutMillis;
        }

        public int readTimeoutMillis() {
            return this.readTimeoutMillis;
        }

        public boolean isFollowRedirects() {
            return this.followRedirects;
        }
    }

这里可以看到,如果ribbon默认的连接时间为10秒,默认的readTimeOut时间为60秒;我们让服务提供者睡眠10秒后提供服务,来测试readTimeOut时间是否合理,代码如下

//服务提供者,休眠10秒
@RestController
public class DemoController {

    @Value("${server.port}")
    String port;

    @RequestMapping("/hi")
    public String home(@RequestParam(value = "name") String name)
    {
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "hi " + name + ",i am from port:" + port;
    }
}

结果

图片.png

idea报错

java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_181]
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_181]
    at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_181]
    at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_181]
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246) ~[na:1.8.0_181]
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:286) ~[na:1.8.0_181]
    at java.io.BufferedInputStream.read(BufferedInputStream.java:345) ~[na:1.8.0_181]
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:735) ~[na:1.8.0_181]
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:678) ~[na:1.8.0_181]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1587) ~[na:1.8.0_181]
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) ~[na:1.8.0_181]
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[na:1.8.0_181]
    at feign.Client$Default.convertResponse(Client.java:82) ~[feign-core-10.4.0.jar:na]

可以看到,在没有主动修改ribbon超时时间时,他默认是60秒,但休眠10秒就已经超时了,事实上及时休眠1秒也会超时,感兴趣的可以测试一下,原因是hystrix默认是1秒超时,这里就需要指定feign的超时时间,具体设置多少需要看各个项目的需求

feign学习到这里就基本完成了,接下来会记录hystrix的学习,欢迎大家来讨论

你可能感兴趣的:(springcloud学习笔记-Feign)