SpringCloud系列——Feign 服务调用

  前言

  前面我们已经实现了服务的注册与发现(请戳:SpringCloud系列——Eureka 服务注册与发现),并且在注册中心注册了一个服务myspringboot,本文记录多个服务之间使用Feign调用。

  Feign是一个声明性web服务客户端。它使编写web服务客户机变得更容易,本质上就是一个http,内部进行了封装而已。

  GitHub地址:https://github.com/OpenFeign/feign

  官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.1.0.RC2/single/spring-cloud-openfeign.html

 

  服务提供者

  提供者除了要在注册中心注册之外,不需要引入其他东西,注意一下几点即可:

  1、经测试,默认情况下,feign只能通过@RequestBody传对象参数

  2、接参只能出现一个复杂对象,例:public Result<List<UserVo>> list(@RequestBody UserVo entityVo) { ... }

  3、提供者如果又要向其他消费者提供服务,又要向浏览器提供服务,建议保持原先的Controller,新建一个专门给消费者的Controller

  

  测试接口

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("list")
    public Result<List<UserVo>> list(@RequestBody UserVo entityVo) {
        return userService.list(entityVo);
    }

    @RequestMapping("get/{id}")
    public Result<UserVo> get(@PathVariable("id") Integer id) {
        return userService.get(id);
    }
}

 

  服务消费者

  消费者maven引入jar

        <!-- feign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

 

  配置文件

  对日期的解析,消费者要跟提供者一致,不然会报json解析错误

#超时时间
feign.httpclient.connection-timeout=30000

#mvc接收参数时对日期进行格式化
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
#jackson对响应回去的日期参数进行格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

 

  服务调用

  1、springdatejpa 应用名称,是服务提供者在eureka注册的名字,Feign会从注册中心获取实例

  2、如果不想启动eureka服务,直连本地开发:@FeignClient(name = "springdatejpa", path = "/user/",url = "http://localhost:10086"),或者无eureka,调用第三方服务,关闭eureka客户端      (eureka.client.enabled=false),url直接指定第三方服务地址,path指定路径,接口的方法指定接口

  3、如果使用@RequestMapping,最好指定调用方式

  4、消费者的返回值必须与提供者的返回值一致,参数对象也要一致

  5、2019-05-21补充:如需进行容错处理(服务提供者发生异常),则需要配置fallback,如果需要获取到报错信息,则要配置fallbackFactory<T>,例:

fallback = MyspringbootFeignFallback.class,fallbackFactory = MyspringbootFeignFallbackFactory.class
/**
 * 容错处理(服务提供者发生异常,将会进入这里)
 */
@Component
public class MyspringbootFeignFallback implements MyspringbootFeign {
    @Override
    public Result<UserVo> get(Integer id) {
        return Result.of(null,false,"糟糕,系统出现了点小状况,请稍后再试");
    }

    @Override
    public Result<List<UserVo>> list(UserVo entityVo) {
        return Result.of(null,false,"糟糕,系统出现了点小状况,请稍后再试");
    }
}
/**
 * 只打印异常,容错处理仍交给MyspringbootFeignFallback
 */
@Component
public class MyspringbootFeignFallbackFactory implements FallbackFactory<MyspringbootFeign> {
    private final MyspringbootFeignFallback myspringbootFeignFallback;

    public MyspringbootFeignFallbackFactory(MyspringbootFeignFallback myspringbootFeignFallback) {
        this.myspringbootFeignFallback = myspringbootFeignFallback;
    }

    @Override
    public MyspringbootFeign create(Throwable cause) {
        cause.printStackTrace();
        return myspringbootFeignFallback;
    }
}

 

  更多@FeignClient注解参数配置,请参阅官方文档

@FeignClient(name = "springdatejpa", path = "/user/")
public interface MyspringbootFeign {

    @RequestMapping(value = "get/{id}")
    Result<UserVo> get(@PathVariable("id") Integer id);

    @RequestMapping(value = "list", method = RequestMethod.GET)
    Result<List<UserVo>> list(@RequestBody UserVo entityVo);
}
    /**
     * feign调用
     */
    @GetMapping("feign/get/{id}")
    Result<UserVo> get(@PathVariable("id") Integer id){
        return myspringbootFeign.get(id);
    }


    /**
     * feign调用
     */
    @GetMapping("feign/list")
    Result<List<UserVo>> list(UserVo userVo){
        return myspringbootFeign.list(userVo);
    }

 

  启动类

  启动类加入注解:@EnableFeignClients

@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class MyspringbootApplication{

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

}

 

  效果

  成功注册两个服务

   

  成功调用

 

  

  报错记录

  1、启动时报了个SQL错误

  解决:配置文件连接数据时指定serverTimezone=GMT%2B8

 

  2、当我将之前搭好的一个springboot-springdata-jpa整合项目在eureka注册时出现了一个报错

  然后在网上查了下说是因为springboot版本问题(请戳:http://www.cnblogs.com/hbbbs/articles/8444013.html),之前这个项目用的是2.0.1.RELEASE,现在要在eureka注册,pom引入了就出现了上面的报错

        <!-- eureka-client -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!-- actuator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

  解决:升级了springboot版本,2.1.0,项目正常启动

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <!--<version>2.0.1.RELEASE</version>-->
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

 

  代码开源

  代码已经开源、托管到我的GitHub、码云:

  GitHub:https://github.com/huanzi-qch/springCloud

  码云:https://gitee.com/huanzi-qch/springCloud

转载于:https://www.cnblogs.com/huanzi-qch/p/10135946.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值