SpringCloud 声明试服务调用Feign
Posted Gggoblin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringCloud 声明试服务调用Feign相关的知识,希望对你有一定的参考价值。
利用fegin去调用服务:
先修改两个HELLO-SERVER服务中添加
@GetMapping("/hello1")
public String hello(@RequestParam String name){
return "Hello" + name;
}
@GetMapping("/hello2")
public User hello(@RequestHeader String name, @RequestHeader Integer age){
return new User(name,age);
}
@PostMapping("/hello3")
public String hello(@RequestBody User user){
return "hello"+user.getName()+","+user.getAge();
}
User实体类
public class User implements Serializable{
private static final long serialVersionUID = 2066603420531796503L;
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
首先引入pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
然后在application中加上如下注解:
@EnableDiscoveryClient
@EnableFeignClients
application.properties配置文件
server.port=9001
spring.application.name=feign-consumer
eureka.client.service-url.defaultZone=http://localhost:8877/eureka/,http://localhost:8898/eureka/
编写feign客户端
@FeignClient("hello-server")
public interface FeignService {
@RequestMapping("/hello")
String hello();
@GetMapping("/hello1")
String hello(@RequestParam("name") String name);
@GetMapping("/hello2")
User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
@PostMapping("/hello3")
String hello(@RequestBody User user);
}
控制层调用demo
@RestController
public class FeignController {
@Resource
private FeignService feignService;
@RequestMapping("/feign")
public String feign(){
return feignService.hello();
}
@RequestMapping("/feign2")
public String feign2(){
String str1 = feignService.hello("goblin");
String str2 = feignService.hello("goblin",22).toString();
String str3 = feignService.hello(new User("goblin", 22));
return str1 + " "+ str2 +" " + str3 ;
}
}
===========================================待补充============================================
以上是关于SpringCloud 声明试服务调用Feign的主要内容,如果未能解决你的问题,请参考以下文章
SpringCloud无废话入门03:Feign声明式服务调用
Spring Cloud第七篇 | 声明式服务调用Feign