首先在中台引入pox:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.0.3</version>
</dependency>
创建一个Service接口:
package com.zhisen.cslcps.service;
import java.util.Map;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("cslcp")
public interface FeignService {
@GetMapping("/test")
public Map<String,Object> test1();
@DeleteMapping("/d1")
public void restTemplatedelete1();
@DeleteMapping("/d2")
public void restTemplatedelete2(@RequestParam Map<String, Object> result);
@DeleteMapping("/d3")
public void restTemplatedelete3(@RequestBody Map<String, Object> result);
// 传递参数为Param
@PostMapping("/test3")
public Map<String, Object> restTemplatepostparam(@RequestParam Map<String, Object> result);
// 传递参数为body
@PostMapping("/test2")
public Map<String, Object> restTemplatepost(@RequestBody Map<String, Object> result);
// 传递参数为url或者formdata
@GetMapping("/test1")
public Map<String, Object> restTemplate(@RequestParam Map<String, Object> result);
}
@FeignClient("cslcp") 中的内容是服务的名称,所有的方法的返回值和参数都与普通工程中的接口一一对应。
注意:如果参数类型为一个实体,而你的方法为GetMapping会报错,原因是因为实体会再body中传输,这时,你可以将普通工程中的方法改为post,或者添加拦截器等等。
再在中台的主类中加入;
@EnableFeignClients
这样就可以直接在controller中直接调用service接口中的方法,就可以实现调用其他服务的接口了。
制作整理不易,以上内容均为原创(参考了部分官方文档和老师整理的案例)。如要引用请附上本文链接,如有疑问可以在评论区畅所欲言,作者看到会第一时间回复,欢迎交流!
本文介绍了如何在Spring Cloud中引入Pox依赖,创建FeignService接口,并通过@FeignClient注解指定服务名。详细展示了GET、DELETE、POST请求的方法定义,包括参数类型和使用场景。同时提到了参数类型为实体时可能会遇到的问题及解决办法,并在主类中启用FeignClients。最后,强调了直接在Controller中调用Service接口即可实现跨服务调用。

1281

被折叠的 条评论
为什么被折叠?



