微服务Feign调用示例
最后更新于:2022-04-02 07:10:54
# 微服务Feign接口调用示例
>[info] Version: 2.4+
[TOC]
本示例以服务(jeecg-system)调用服务(jeecg-demo)为例讲解feign调用说明
## jeecg-demo中编写服务接口
编写接口
~~~
public interface JeecgDemoService {
Result getMessage(String name);
}
~~~
编写实现类
~~~
@Service
public class JeecgDemoServiceImpl implements JeecgDemoService {
@Override
public Result getMessage(String name) {
return Result.OK("Hello" + name);
}
}
~~~
编写服务接口
~~~
@RestController
@RequestMapping("/test")
public class JeecgDemoProvider {
@Resource
private JeecgDemoService jeecgDemoService;
@GetMapping("/getMessage")
public Result getMessage(@RequestParam String name) {
return jeecgDemoService.getMessage(name);
}
}
~~~
## 方式一: jeecg-system中编写feign客户端
a. 启动类 加上 `@EnableFeignClients` 注解。
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/6a/59/6a5967047f9da0083003d3e9db700f4e_805x436.png)
b. 编写feign客户端
~~~
//jeecg-cloud-demo的服务名是 jeecg-demo
@FeignClient(value = "jeecg-demo")
@Component
public interface JeecgTestClient {
@GetMapping(value = "/test/getMessage")
Result getMessage(@RequestParam("name") String name);
}
~~~
c. 编写测试方法
~~~
@RestController
@RequestMapping("/sys/test")
@Api(tags = "feign测试")
public class JeecgTestFeignTest {
//注入feign客户端
@Autowired
private JeecgTestClient jeecgTestClient;
@GetMapping("getMessage")
@ApiOperation(value = "测试feign", notes = "测试feign")
public Result getMessage() {
return jeecgTestClient.getMessage("jeecg-boot");
}
}
~~~
## 方式二: jeecg-cloud-system中编写动态feign客户端
a. 启动类 加上 `@EnableFeignClients` 注解。
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/6a/59/6a5967047f9da0083003d3e9db700f4e_805x436.png)
a. 编写feign调用接口
~~~
public interface JeecgTestClient {
@GetMapping(value = "/test/getMessage")
Result getMessage(@RequestParam("name") String name);
}
~~~
c. 编写测试方法
~~~
@RestController
@RequestMapping("/sys/test")
@Api(tags = "feign测试")
public class JeecgTestFeignTest {
@Autowired
private JeecgFeignService jeecgFeignService;
@GetMapping("getMessage")
@ApiOperation(value = "测试feign", notes = "测试feign")
public Result getMessage() {
JeecgTestClient jeecgTestClient = jeecgFeignService.newInstance(JeecgTestClient.class, "jeecg-demo");
return jeecgTestClient.getMessage("jeecg-boot");
}
}
~~~
';