1. 添加pom文件
版本号根据实际开发进行定位
<!--服务调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
2. 在服务模块创建
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping(value = "/feign/test")
public class TestFeignController {
@RequestMapping(value = "test")
public String test(String data) {
System.out.println(data);
return data + "没问题";
}
}
3. 创建feign虚拟客户端
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Component
@FeignClient(value = "server-stare")//此名称为消费提供者注册的服务名称
public interface StartClient {
// 指向controller接口
@RequestMapping(value = "/feign/test/test",method = RequestMethod.POST)
String feignTest(@RequestParam String data);
}
4. 引入feign
引入feign启动类需要添加这几个
// 这里注意了如果你的feign是单独的一个模块,需要指向该模块例:"cc.vace.cloud.**.feign",如果feign在当前模块下,则不需要()中的内容
@EnableFeignClients({"cc.vace.cloud.**.feign"})
@EnableDiscoveryClient
@EnableEurekaClient
配置文件
#feign的配置,连接超时及读取超时配置
feign:
client:
config:
default:
connectTimeout: 5000 #
readTimeout: 5000
loggerLevel: basic
使用feign
@Resource
private StartClient startClient;
@RequestMapping(value = "/test")
public String feign(@RequestBody Map<String, String> map) {
return startClient.feignTest("123");
}
测试
这里是测试的,项目的构建与这差不多,feign更推荐单独一个模块,而不是一个模块里有一个feign