1. 前言:

开发微服务,免不了会有微服务之间的调用。在这里,我们使用的是openfeign 。因为微服务间的调用不需要通过zuul,因此就可以跳过token验证这一步,但是也没有了zuul的服务转发这个功能。

为了模拟微服务间的调用,我们在my-user微服务中新建一个接口,让my-student微服务来调用这个接口。

2. UserController.java 修改

新建一个hello的接口,很简单,只有一个打印语句。

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public void hello(){
    System.out.println("hello");
}
  • 1.
  • 2.
  • 3.
  • 4.

3. 加入依赖

<!--openfein-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

4. StuApplication.java修改

加入注解

@EnableFeignClients
  • 1.

5. 新建UserFeign接口

在my-student微服务中service包中新建接口UserFeign

package com.student.service;

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

// 微服务的名字
@FeignClient(name = "my-user")
public interface UserFeign {
    // 接口地址
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public void hello();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

6. StuController.java 修改

6.1 引入UserFeign
@Autowired
UserFeign userFeign;
  • 1.
  • 2.
6.2 使用UserFeign

我们在学生查询的接口中调用my-user的hello接口,来模拟调用,修改如下:

//学生查询
@RequestMapping(value = "/get", method = RequestMethod.POST)
public JSONObject getStudent(@RequestBody JSONObject jsonObject){
    //获取学生信息
    List<Student> studentList = stuService.getStu(jsonObject);
    //获取学生数量
    int stuCount = stuService.getStuCount(jsonObject);

    //微服务之前通信
    userFeign.hello();

    JSONObject result = new JSONObject();
    result.put("studentList",studentList);
    result.put("stuCount",stuCount);
    return result;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

因为hello这个接口没有返回值,直接使用 userFeign.hello() 即可。

7. 验证:

当我们在前端调用学生查询这个接口的时候,观察一下my-user的控制台输出。

微服务和VUE入门教程(23): 微服务之间的调用_java

可以打印出“hello”,说明已成功调用。