概述

被调用的服务已经注册到Nacos,注册步骤查看博客:https://blog.zoutl.cn/483.html

注册两个服务到Nacos,一个名为nacos-order(订单微服务),另一个名为nacos-stock(库存微服务),订单微服务调用库存微服务

实现过程

库存微服务

在库存微服务中添加一个被调用的方法(Controller类)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.ledao.controller;

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

import java.util.Date;

/**
* @author LeDao
* @company
* @create 2022-03-28 20:20
*/
@RestController
@RequestMapping("/stock")
public class StockController {

@RequestMapping("/test")
public String test(String info) {
return new Date() + " : " + info;
}
}

订单微服务

引入依赖,OpenFeign依赖是用来调用服务的

1
2
3
4
5
<!-- OpenFeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

新建一个Service类调用服务,@FeignClient注解用来确定调用的是哪个微服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.ledao.feign;

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

/**
* @author LeDao
* @company
* @create 2022-03-28 20:42
*/
@FeignClient("nacos-stock")
public interface StockFeignService {

/**
* 调用服务
*
* @param info
* @return
*/
@RequestMapping("/stock/test")
String test(@RequestParam("info") String info);
}

启动类添加@EnableFeignClients注解,参数为调用服务的Service类所在的包(也就是使用了@FeignClient注解的类所在的包),这样才能调用服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.ledao;

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

/**
* @author LeDao
* @company
* @create 2022-03-28 19:40
*/
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients(basePackages = "com.ledao.feign")
public class NacosOrderApplication {

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

测试调用(使用Controller类)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.ledao.controller;

import com.ledao.feign.StockFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author LeDao
* @company
* @create 2022-03-28 20:52
*/
@RestController
@RequestMapping("/order")
public class OrderController {

private StockFeignService stockFeignService;

@Autowired
public void setStockFeignService(StockFeignService stockFeignService) {
this.stockFeignService = stockFeignService;
}

@RequestMapping("/test")
public String test() {
return stockFeignService.test("调用库存微服务");
}
}

测试

先启动库存微服务,再启动订单微服务,然后通过localhost:8081/order/test调用(具体端口看订单微服务的application.yml配置文件)