当前位置: 移动技术网 > IT编程>开发语言>Java > SpringCloud之Feign:REST客户端

SpringCloud之Feign:REST客户端

2019年11月16日  | 移动技术网IT编程  | 我要评论

在spring cloud集群中,各个角色的通信基于rest服务,在调用服务时,需要使用rest客户端,常用,除了使用spring自带的resttemplate,也可使用另一个rest客户端:feign。

使用feign时,可以使用自带注解或第三方注解来修饰接口,使得接口具有访问web service的能力。
feign还支持插件式的编码器和解码器,对请求和响应进行不同的封装和解析。
spring cloud将feign集成到netflix项目中,与eureka、ribbon集成时,feign就具有负载均衡的功能。
feign在spring boot web项目的使用例子可参考:《spring boot 2 发布与调用rest服务

下面例子为在spring cloud的使用。
开发工具:intellij idea 2019.2.3

一、服务器端

1、创建项目

idea中创建一个新的springboot项目,名称为“spring-feign-server”,springboot版本选择2.1.10,在选择dependencies(依赖)的界面勾选spring cloud discovert ->
eureka server,创建完成后的pom.xml配置文件自动添加springcloud最新稳定版本依赖,当前为greenwich.sr3。
pom.xml完整内容如下:

<?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.1.10.release</version>
        <relativepath/> <!-- lookup parent from repository -->
    </parent>
    <groupid>com.example</groupid>
    <artifactid>spring-feign-server</artifactid>
    <version>0.0.1-snapshot</version>
    <name>spring-feign-server</name>
    <description>demo project for spring boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>greenwich.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-test</artifactid>
            <scope>test</scope>
        </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、修改配置application.yml

修改端口号为8761;取消将自己信息注册到eureka服务器,不从eureka服务器抓取注册信息。

server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

3、修改启动类代码springfeignserverapplication.java

增加注解@enableeurekaserver

package com.example.springfeignserver;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cloud.netflix.eureka.server.enableeurekaserver;

@springbootapplication
@enableeurekaserver
public class springfeignserverapplication {
    public static void main(string[] args) {
        springapplication.run(springfeignserverapplication.class, args);
    }
}

二、服务提供者

1、创建项目

idea中创建一个新的springboot项目,除了名称为“spring-feign-provider”,其它步骤和上面创建服务器端一样。

2、修改配置application.yml

spring:
  application:
    name: spring-feign-provider
eureka:
  instance:
    hostname: localhost
  client:
    serviceurl:
      defaultzone: http://localhost:8761/eureka/

3、添加一个实体类user.java

package com.example.springfeignprovider;

public class user {
    string name;
    integer age;

    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public integer getage() {
        return age;
    }
    public void setage(integer age) {
        this.age = age;
    }
}

4、修改启动类代码springfeignproviderapplication.java

增加注解@enableeurekaclient和@restcontroller;
让类在启动时读取控制台输入,决定使用哪个端口启动服务器;
增加2个测试用的控制器方法。

package com.example.springfeignprovider;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.builder.springapplicationbuilder;
import org.springframework.cloud.netflix.eureka.enableeurekaclient;
import org.springframework.http.mediatype;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

import javax.servlet.http.httpservletrequest;
import java.util.scanner;

@springbootapplication
@enableeurekaclient
@restcontroller
public class springfeignproviderapplication {

    public static void main(string[] args) {
        //springapplication.run(springfeignproviderapplication.class, args);
        scanner scan = new scanner(system.in);
        string port = scan.nextline();
        new springapplicationbuilder(springfeignproviderapplication.class).properties("server.port=" + port).run(args);
    }

    @requestmapping("/hello")
    public string hello(httpservletrequest request) {
        return "hello world." + request.getserverport();
    }

    @requestmapping(value="/user/{name}", produces = mediatype.application_json_value)
    public user user(@pathvariable string name) {
        user u = new user();
        u.setname(name);
        u.setage(30);
        return u;
    }
}

三、服务调用者

1、创建项目
idea中创建一个新的springboot项目,名称为“spring-feign-invoker”,springboot版本选择2.1.10,在选择dependencies(依赖)的界面勾选spring cloud discovert -> eureka server,spring cloud routing -> openfeign。
pom.xml完整内容如下:

<?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.1.10.release</version>
        <relativepath/> <!-- lookup parent from repository -->
    </parent>
    <groupid>com.example</groupid>
    <artifactid>spring-feign-invoker</artifactid>
    <version>0.0.1-snapshot</version>
    <name>spring-feign-invoker</name>
    <description>demo project for spring boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>greenwich.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.cloud</groupid>
            <artifactid>spring-cloud-starter-openfeign</artifactid>
        </dependency>

        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </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、修改配置application.yml

server:
  port: 9000
spring:
  application:
    name: spring-feign-invoker
eureka:
  instance:
    hostname: localhost
  client:
    serviceurl:
      defaultzone: http://localhost:8761/eureka/

3、添加一个实体类user.java

package com.example.springfeigninvoker;

public class user {
    string name;
    integer age;

    public string getname() {
        return name;
    }
    public void setname(string name) {
        this.name = name;
    }
    public integer getage() {
        return age;
    }
    public void setage(integer age) {
        this.age = age;
    }
}

4、添加一个客户端接口userclient.java

package com.example.springfeigninvoker;

import org.springframework.cloud.openfeign.feignclient;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;

//声明调用的服务名称
@feignclient("spring-feign-provider")
public interface userclient {
    @requestmapping(method = requestmethod.get, value = "/hello")
    string hello();

    @requestmapping(method = requestmethod.get, value = "/user/{name}")
    user getuser(@pathvariable("name") string name);
}

5、修改启动类代码cloudinvokerapplication.java

增加注解@enableeurekaclient和@enablefeignclients。

package com.example.springfeigninvoker;

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 springfeigninvokerapplication {
    public static void main(string[] args) {
        springapplication.run(springfeigninvokerapplication.class, args);
    }
}

6、添加控制器 invokercontroller.java 

package com.example.springfeigninvoker;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.http.mediatype;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
@configuration
public class invokercontroller {
    @autowired
    private userclient userclient;

    @requestmapping(value = "/invokehello", method = requestmethod.get)
    public string invokehello(){
        return userclient.hello();
    }

    @requestmapping(value = "/invokeuser", method = requestmethod.get, produces = mediatype.application_json_value)
    public string invokeuser(){
        return userclient.getuser("小明").getage().tostring();
    }
}

四、测试

1、启动服务器端。
浏览器访问http://localhost:8761/,正常
2、启动两个服务提供者,在控制台中分别输入8080和8081启动。
(1)浏览器访问 http://localhost:8080/user/小明
输出:{"name":"小明","age":30}
(2)浏览器访问 http://localhost:8081/user/小强
输出:{"name":"小强","age":30}
3、启动服务调用者。
(1)浏览器访问http://localhost:9000/invokehello,页面显示在下面8080和8081端口之间切换:
hello world.8080
hello world.8081
(2)浏览器访问http://localhost:9000/invokeuser,输出:
30

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网