Springboot2.x使用feign优雅调用跨项目接口

1.首先实现server项目,提供数据接口

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.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.frank</groupId>
    <artifactId>feign-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>feign-server</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

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

</project>

application.properties

server.port=8081
spring.application.name=user-service
server.servlet.context-path=/api

user

package com.frank.feignserver;

/**
 * @author 小石潭记
 * @date 2020/6/22 21:42
 * @Description: ${todo}
 */
public class User {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public User() {
    }
}
ServerController
package com.frank.feignserver;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 小石潭记
 * @date 2020/6/22 21:40
 * @Description: ${todo}
 */
@RestController()
public class ServerController {

    @GetMapping("/getSuccessInfo")
    public Map<String,Object> getSuccessInfo(){
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "success");
        map.put("data", new User(1,"小石潭记",26));
        return map;
    }

    @GetMapping("/getFailInfo")
    public Map<String,Object> getFailInfo(){
        Map<String,Object> map = new HashMap<>();
        map.put("code", 404);
        map.put("msg", "fail");
        map.put("data", null);
        return map;
    }
}
FeignServerApplication
package com.frank.feignserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FeignServerApplication {

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

}

启动测试:(这里只是简单返回固定的数据用于测试而已)

http://localhost:8081/api/getSuccessInfo

http://localhost:8081/api/getFailInfo

服务端完成成功。

*********feign客户端*********

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.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.frank</groupId>
    <artifactId>feign-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>feign-client</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

    </dependencies>

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

</project>

这里使用的是Spring Cloud Starter OpenFeign和springboot1.x不一致,这里需要注意下。

application.properties

server.port=8082
spring.application.name=feign-client
# 开启熔断
feign.hystrix.enabled=true
UserFeignClient
package com.frank.feignclient;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 小石潭记
 * @date 2020/6/22 21:48
 * @Description: ${todo}
 */
@FeignClient(
        //服务名
        name = "user-service",
        //服务地址
        url = "http://localhost:8081/api",
        fallback = UserHihystric.class
)
public interface UserFeignClient {

    //对应的服务里的接口地址,及请求方式
    @RequestMapping(value = "/getSuccessInfo", method = RequestMethod.GET)
    @ResponseBody
    String getSuccessInfo();

    @RequestMapping(value = "/getFailInfo", method = RequestMethod.GET)
    @ResponseBody
    String getFailInfo();

}

UserHihystric(服务异常时执行,熔断)
package com.frank.feignclient;

import org.springframework.stereotype.Component;

/**
 * @author 小石潭记
 * @date 2020/6/23 20:31
 * @Description: ${todo}
 */
@Component
public class UserHihystric implements UserFeignClient {
    @Override
    public String getSuccessInfo(){
        return "getSuccessInfo serve is bad.";
    }

    @Override
    public String getFailInfo() {
        return "getFailInfo serve is bad.";
    }

}

UserController

package com.frank.feignclient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 小石潭记
 * @date 2020/6/20 21:38
 * @Description: ${todo}
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserFeignClient userFeignClient;

    @GetMapping("/getSuccessInfo")
    public Object getSuccessInfo(){
        return userFeignClient.getSuccessInfo();
    }

    @GetMapping("/getFailInfo")
    public Object getFailInfo(){
        return userFeignClient.getFailInfo();
    }
}
MyAdvice(这里暂时可以忽略)
package com.frank.feignclient;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 小石潭记
 * @date 2020/6/22 21:07
 * @Description: ${todo}
 */
@ControllerAdvice
public class MyAdvice implements ResponseBodyAdvice<Object> {

    /**
     *  判断哪些需要拦截 return true 就会执行beforeBodyWrite
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        System.out.println("==>beforeBodyWrite:" + obj.toString() + ","
                + methodParameter);
        return obj;
    }
}
FeignClientApplication
package com.frank.feignclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard
public class FeignClientApplication {

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

}

这里需要在启动类添加@EnableFeignClients注解

最后启动测试:

http://localhost:8082/user/getSuccessInfo

http://localhost:8082/user/getFailInfo

关闭服务端:返回熔断里面的内容。

成功获取服务端的数据,搞定!!!

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
com.netflix.feign是一个声明式的Web Service客户端,它简化了编写Web服务客户端的操作。使用Feign,可以通过注释接口来定义客户端,而无需编写实现代码。以下是使用Feign的步骤: 1.添加依赖 在Maven项目中,将以下依赖添加到pom.xml文件中: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.5.RELEASE</version> </dependency> ``` 2.创建接口 创建一个用于调用Web服务的接口,并使用注释定义它。例如,以下是一个使用GET请求获取用户信息的接口: ``` @FeignClient(name = "user-service") public interface UserClient { @GetMapping("/users/{id}") User getUser(@PathVariable("id") Long id); } ``` 在此示例中,@FeignClient注释指定要调用的服务的名称,并且getUser方法使用@GetMapping注释定义了一个GET请求。 3.注入客户端 在应用程序中注入客户端,并将其用于调用Web服务。例如,以下是如何在Spring Boot应用程序中注入客户端: ``` @RestController public class UserController { @Autowired private UserClient userClient; @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userClient.getUser(id); } } ``` 在此示例中,UserController使用@Autowired注释注入了UserClient,并将其用于调用getUser方法。 4.配置客户端 通过配置文件或使用Java代码,可以对客户端进行各种配置。例如,以下是如何配置Feign客户端的超时时间: ``` feign.client.config.default.connectTimeout=5000 feign.client.config.default.readTimeout=5000 ``` 在此示例中,配置文件设置默认Feign客户端的连接超时和读取超时时间为5秒。 以上就是使用com.netflix.feign的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值