SpringCloud之Feign

前面的话】书接上文,本文的某些知识依赖我的第一篇SpringCLoud的文章:SpringCloud之Eureka,如果没有看过可以先移步去看一下。另外在微服务架构中,业务都会被拆分成一个个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。上一篇文章已经讲过ribbon+rest这种方式了,这一片博文主要讲feign的应用。


壹、Feign的简介

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

简而言之:

  • Feign 采用的是基于接口的注解
  • Feign 整合了ribbon

贰、准备工作

新建一个feign子工程lovin-feign-client,用于后面的操作。下面是主要的pom依赖:

<parent>
        <artifactId>lovincloud</artifactId>
        <groupId>com.eelve.lovincloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>lovin-feign-client</artifactId>
    <version>0.0.1</version>
    <name>lovinfeignclient</name>
    <description>feignclient测试</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • 这里为了安全,我这里还是添加spring-boot-starter-security
server:
  port: 8806   # 服务端口号
spring:
  application:
    name: lovinfeignclient     # 服务名称
  security:
    basic:
      enabled: true
    user:
      name: lovin
      password: ${REGISTRY_SERVER_PASSWORD:lovin}
eureka:
  client:
    serviceUrl:
      defaultZone: http://lovin:lovin@localhost:8881/eureka/   # 注册到的eureka服务地址
feign:
  hystrix:
    enabled: true
  • 配置spring-boot-starter-security,这里为了方便我这里放开所有请求
package com.eelve.lovin.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @ClassName SecurityConfig
 * @Description TDO
 * @Author zhao.zhilue
 * @Date 2019/8/16 14:13
 * @Version 1.0
 **/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()
                .and().csrf().disable();
    }
}
  • 在主类上添加@EnableFeignClients@EnableHystrix ,当然也需要注册到注册中心:
package com.eelve.lovin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @ClassName LovinFeignClientApplication
 * @Description TDO
 * @Author zhao.zhilue
 * @Date 2019/8/15 17:17
 * @Version 1.0
 **/
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableHystrix
public class LovinFeignClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(LovinFeignClientApplication.class,args);
    }
}
  • 添加一个远程调用的服务端FeignRemoteService,并且配置feign调用信息:
package com.eelve.lovin.service;

import com.eelve.lovin.hystrix.FeignRemoteServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @ClassName FeignRemoteService
 * @Description TDO
 * @Author zhao.zhilue
 * @Date 2019/8/15 17:18
 * @Version 1.0
 **/
@FeignClient(value = "lovineurkaclient",fallback = FeignRemoteServiceImpl.class)
public interface FeignRemoteService {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello();
}
  • 添加熔断器调用方法:新建FeignRemoteServiceImpl实现FeignRemoteService接口:
package com.eelve.lovin.hystrix;

import com.eelve.lovin.service.FeignRemoteService;
import org.springframework.stereotype.Component;

/**
 * @ClassName FeignRemoteServiceImpl
 * @Description TDO
 * @Author zhao.zhilue
 * @Date 2019/8/15 17:31
 * @Version 1.0
 **/
@Component
public class FeignRemoteServiceImpl implements FeignRemoteService {
    @Override
    public String hello() {
        return "hystrix起作用了";
    }
}
  • 最后新建FeignController,来消费服务:
package com.eelve.lovin.controller;

import com.eelve.lovin.service.FeignRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName FeignController
 * @Description TDO
 * @Author zhao.zhilue
 * @Date 2019/8/15 17:21
 * @Version 1.0
 **/
@RestController
public class FeignController {

    @Autowired
    FeignRemoteService feignRemoteService;

    @GetMapping(value = "/getHello")
    public String getHello() {
        return feignRemoteService.hello();
    }
}

叁、启动测试

  • 依次启动eureka的服务端和两个客户端,以及新建的lovin-feign-client


    我们可以看到服务已经全部启动成功

    我们可以看到服务已经全部启动成功

  • 然后访问http://localhost:8806/getHello
    我们可以看到已经可以通过feign调到我们建立的eureka客户端了

    我们可以看到已经可以通过feign调到我们建立的eureka客户端了
  • 再次请求接口观察返回


    我们可以看到我们调到了通过feign调用ribbon负载的另外一个接口

    我们可以看到我们调到了通过feign调用ribbon负载的另外一个接口了,到这里我们就已经弄好了一个简单的ribbon负载。

肆、添加Hystrix Dashboard断路器监控

  • 添加需要的pom依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    <version>2.1.2.RELEASE</version>
</dependency>
  • 在主类上添加@EnableHystrixDashboard,开启断路器监控,并且配置HystrixMetricsStreamServlet
package com.eelve.lovin;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

/**
 * @ClassName LovinFeignClientApplication
 * @Description TDO
 * @Author zhao.zhilue
 * @Date 2019/8/15 17:17
 * @Version 1.0
 **/
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableHystrix
@EnableHystrixDashboard
public class LovinFeignClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(LovinFeignClientApplication.class,args);
    }

    @Bean
    public ServletRegistrationBean getServlet(){
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}
默认的集群监控:通过URL http://turbine-hostname:port/turbine.stream开启,实现对默认集群的监控。
指定的集群监控:通过URL http://turbine-hostname:port/turbine.stream?cluster=[clusterName]开启,实现对clusterName的监控。
单体应用监控:通过URL http://hystrix-app:port/hystrix.stream开启,实现对某个具体的服务监控
  • 添加监控模式查看详情,这里选择第三个单体应用
添加监控接口

监控详情

这样我们就完成了熔断器的监控,当然具体含义有待下一步深究。

伍、网络架构

  • 我们可以看到我们调用的服务不再是像再上一篇文章中的直接访问对应的服务,而是通过feign的Ribbon的负载均衡的去调用的,而且这里说明一点,Ribbon的默认机制是轮询。


    目前的网络架构

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容