Spring Cloud 快速入门系列之feign–微服务之间的调用

我们将一个大的应用拆成多个小的服务之后,紧接着的一个问题就是,原本都在一个项目里,方法我可以随便调用,但是拆开后,原来的方法就没法直接调用了,这时候要怎么办?

Spring Cloud提供了feign,能够轻松解决这个问题,feign能让我们调用远程服务方法就像调用本地方法一样,调用者完全感觉不到实在调用远程服务。

其底层其实就是使用了RPC,对网络的请求和响应做了解析,在这里对RPC先不做讲解,我们重点来了解如何使用feign来调用其他微服务。

feign这个功能是不是听起来很神奇,但是用起来确实很简单,我们一起来看看。

实操O(∩_∩)O

1、首先复制一个service-a的项目,我们起名叫service-b

2、在service-b的pom.xml文件中,添加feign的依赖

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

3、在应用主类添加@EnableFeignClients,开启feign支持

package com.itzhimei.serviceb;

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

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceBApplication {

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

}

4、在service-b中添加一个抽象接口ServiceA

package com.itzhimei.serviceb.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient("service-a")
public interface ServiceA {

    @GetMapping(value = "/getInfo")
    public String getInfo();

}

这个接口的作用就是,让serviceb调用servicea的方法就像调用本地方法一样。class上的注解@FeignClient(“service-a”),就表示通过serviceA的serviceId,找到serviceA服务,通过@GetMapping(value = “/getInfo”)来对应到serviceA中的方法。

5、最后就是调用ServiceA了,写一个调用的Controller

package com.itzhimei.serviceb.controller;

import com.itzhimei.serviceb.feign.ServiceA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServiceBController {

    @Autowired
    ServiceA serviceA;

    @RequestMapping(value="helloFeign", method = RequestMethod.GET)
    public String helloFeign() {
        return serviceA.getInfo();
    }

}

本地访问ServiceB的helloFeign:http://192.168.0.106:1120/helloFeign

输出结果:名字是:张三,年龄是:20

到这里,微服务的相互调用就成功了,是不是超级简单,通过几步配置,就完成了原来复杂的网络之间的调用。