(四)Spring Cloud Feign 声明式调用

上一章讲了Ribbon的负载均衡,并且使用RestTemplate进行了调用,本章讲解另外一种负载均衡的调用

即,Feign的声明式调用

和上一章一样,我们将启动1个eureka-server 用于服务的注册,2个eureka-client  模拟2个客户端  1个 eureka-feign-client 用于对客户端的声明式调用 

   1. 创建一个maven项目

     在pom中设置 

     <packaging>pom</packaging>


2. 新建eureka-server,端口为7001

主要配置如下

2.1 pom文件

     

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.devin</groupId>
    <artifactId>eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-server</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

     2.2. 启动类

package com.devin.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

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

}

  

     2.3 权限配置类

  

package com.devin.eurekaserver.config;

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

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf
        super.configure(http);
        //开启认证
        http.csrf().disable();
    }
}

 

    2.4  application.yml 配置

 eureka-server 的启动端口为 7001

server:
  port: 7001 #启动端口
spring:
  #应用名称
  application:
    name: eureka-server
  #安全配置
  security:
    basic:
      enabled: true
    user:
      name: dev
      password: 123456

#eureka配置
eureka:
  server:
    #设置扫描失效服务的间隔时间
    eviction-interval-timer-in-ms: 20000
    enable-self-preservation: true
  instance:
    hostname: localhost
    leaseRenewalIntervalInSeconds: 10
    health-check-url-path: /actuator/health
  client:
    register-with-eureka: false  #false:不作为一个客户端注册到注册中心
    fetch-registry: false        #为true时,可以启动,但报异常:Cannot execute request on any known server
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

# health endpoint是否必须显示全部细节。默认情况下, /actuator/health 是公开的,并且不显示细节。
# 设置actuator开关
management:
  security:
    enabled: false
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS

 3. eureka-client 配置

   3.1 pom.xml配置

    

   <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>
            <version>2.1.8.RELEASE</version>
        </dependency>

   3.2 启动类

  

package com.devin.eurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient
@SpringBootApplication
public class EurekaClientApplication {

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

}

 

3.3 新建Controller

 在controller中定义了一个get和一个post请求的方法

package com.devin.eurekaclient.controller;

import com.devin.eurekaclient.vo.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * @author Devin Zhang
 * @className HelloController
 * @description TODO
 * @date 2020/3/28 10:45
 */

@RestController
public class HelloController {

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

    @GetMapping("/sayHello")
    public String sayHello(String name) {
        return "Hello ," + name + " ,this response is from eureka client port:" + port;
    }

    @PostMapping("/login")
    public String login(@RequestBody User user) {
        if (user.getUserName().equals("devin") && user.getUserPass().equals("123456")) {
            return "success from " + port;
        }
        return "fail from " + port;
    }
}

  

 对应的model

  

package com.devin.eurekaclient.vo;

/**
 * @author Devin Zhang
 * @className User
 * @description TODO
 * @date 2020/3/30 13:33
 */

public class User {
    private String userName;
    private String userPass;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPass() {
        return userPass;
    }

    public void setUserPass(String userPass) {
        this.userPass = userPass;
    }
}

 

  3.4 application.yml 配置文件

    后续eureka-client将启动2个端口 7002 和 7003 ,这两个实例将分别在eueka-server 7001 注册

eureka:
  auth:
    user: dev
    password: 123456
  client:
    serviceUrl:
      defaultZone: http://${eureka.auth.user}:${eureka.auth.password}@localhost:7001/eureka/
  instance:
    #使用IP进行注册
    prefer-ip-address: true
    #配置实例的注册ID
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #心跳时间,即服务续约间隔时间(缺省为30s)
    lease-renewal-interval-in-seconds: 5
    #发呆时间,即服务续约到期时间(缺省为90s)
    lease-expiration-duration-in-seconds: 10
    health-check-url-path: /actuator/health
server:
  port: 7002
spring:
  application:
    name: eureka-client

  

 4. eureka-feign-client 

  通过feign去调用eureka-client,feign将自动实现客户端服务调用的负载均衡

    4.1 pom.xml

   

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

        <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>
            <version>2.1.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>10.1.0</version>
        </dependency>

  ps: 后面两个包是为了解决feign的get请求时会报如下错误,同时需要在配置文件中添加 feign.httpclient.enabled=true

{"timestamp":"2020-03-30T02:03:50.634+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported",

    4.2 启动类

   该项目也作为一个client在服务端7001 注册

   

package com.devin.eurekafeignclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class EurekaFeignClientApplication {

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

}

  

4.3 Feign的配置类

  

package com.devin.eurekafeignclient.config;

import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * @author Devin Zhang
 * @className FeignConfig
 * @description TODO
 * @date 2020/3/28 16:50
 */
@Configuration
public class FeignConfig {

    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(100, SECONDS.toSeconds(1), 5);
    }
}

 4.4 Feign去声明式调用eureka-clent的接口服务

    feign将去调用我们再eureka-client中定义的get和post对应的接口

    

package com.devin.eurekafeignclient.service;

import com.devin.eurekafeignclient.config.FeignConfig;
import com.devin.eurekafeignclient.vo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author Devin Zhang
 * @className FeignHelloService
 * @description TODO
 * @date 2020/3/28 16:49
 */
@FeignClient(value = "eureka-client", configuration = FeignConfig.class)
public interface FeignHelloService {

    @GetMapping(value = "/sayHello")
    String sayHello(@RequestParam String name);

    @PostMapping(value = "/login", consumes = "application/json")
    String login(@RequestBody User user);
}

  

  

package com.devin.eurekafeignclient.vo;

/**
 * @author Devin Zhang
 * @className User
 * @description TODO
 * @date 2020/3/30 13:39
 */

public class User {
    private String userName;
    private String userPass;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPass() {
        return userPass;
    }

    public void setUserPass(String userPass) {
        this.userPass = userPass;
    }
}

  4.5 controller测试类

  

package com.devin.eurekafeignclient.controller;

import com.devin.eurekafeignclient.service.FeignHelloService;
import com.devin.eurekafeignclient.vo.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Devin Zhang
 * @className FeignHelloController
 * @description TODO
 * @date 2020/3/28 17:01
 */

@RestController
public class FeignHelloController {

    @Resource
    private FeignHelloService feignHelloService;

    @GetMapping(value = "/sayHelloFromFeign")
    public String sayHelloFromFeign(String name) {
        return feignHelloService.sayHello(name);
    }

    @PostMapping(value = "/loginFromFeign")
    public String sayHelloFromFeign(User user) {
        return feignHelloService.login(user);
    }
}

  

  4.6 eureka-feign-client application.yml 配置

   feigin client 7004 将在eureka-server 7001注册

eureka:
  auth:
    user: dev
    password: 123456
  client:
    serviceUrl:
      defaultZone: http://${eureka.auth.user}:${eureka.auth.password}@localhost:7001/eureka/
  instance:
    #使用IP进行注册
    prefer-ip-address: true
    #配置实例的注册ID
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #心跳时间,即服务续约间隔时间(缺省为30s)
    lease-renewal-interval-in-seconds: 5
    #发呆时间,即服务续约到期时间(缺省为90s)
    lease-expiration-duration-in-seconds: 10
    health-check-url-path: /actuator/health
server:
  port: 7004
spring:
  application:
    name: eureka-feign-client
feign:
  httpclient:
    enabled: true

 5. 测试

  启动 eureka-server  7001

  启动eureka-client 7002,7003

   java -jar eureka-client-0.0.1-SNAPSHOT.jar --server.port=7002

   java -jar eureka-client-0.0.1-SNAPSHOT.jar --server.port=7003

  启动 eureka-feign-client  7004

   

  服务的注册情况如下:

  

  

  验证

   访问get请求 http://localhost:7004/sayHelloFromFeign?name=devin 可以看到调用的eureka-clent在7002和7003之间进行切换

   

 

  Post请求,使用 SoupUI发送post请求,可以看到后端收到参数,自动封装为一个model,返回结果,并且在7002,7003之间负载均衡

  

 

  至此,feign的声明式调用完成。

原文地址:https://www.cnblogs.com/DevinZhang1990/p/12598019.html