SpringCloud学习 - Feign声明式服务调用客户端//接口方式

  1. Feign声明式服务调用客户端//接口方式

书签:

1、小小例子

2、Get多个请求参数处理

 

  1. 小小例子

新建项目:eureka-consumer-feign

pom核心配置:


   org.springframework.cloud
   spring-cloud-starter-openfeign

 

创建接口:FeignTest.java

package cn.ywj.eurekaconsumerfeign;

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

@FeignClient("eureka-provider")// 指定要访问的服务提供者
public interface FeignTest {

    @RequestMapping(method = RequestMethod.GET, value = "/t")// 服务提供的请求地址
    public String t();
}

 

项目启动类:EurekaConsumerFeignApplication.java, 核心注解:@EnableFeignClients

package cn.ywj.eurekaconsumerfeign;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableFeignClients
public class EurekaConsumerFeignApplication {

   @Autowired
   private FeignTest feignTest;

   @RequestMapping("/t")
   public String t(){
      return feignTest.t();
   }

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

 

运行项目访问,一样可以得到结果。Feign集成了Ribbon,也可以注入IRule使用各种负载均衡功能。

  1. Get多个请求参数处理

单参数请求参数时,没什么问题,多参数时,有会问题,,,

当FeignTest接口中添加新的方法

@RequestMapping(method = RequestMethod.GET, value = "/t2")
public User t2(User user);

 

然后Controller请求

@RequestMapping("/t2")
public String t2(User user){
   User user1 = feignTest.t2(user);
   return user1 == null ? "null" : user1.getName()+":"+user1.getAge();
}

 

http://127.0.0.1:8083/t2?name=ywj&age=17 

此时会报错:

content:{"timestamp":"2018-10-10T09:14:43.547+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/t2"}

 

处理方法:

  • 第一种:把user参数拆分成name,age

FeignTest.java

@RequestMapping(method = RequestMethod.GET, value = "/t3")
public User t3(@RequestParam("name") String name, @RequestParam("age") Integer age);

 

eureka-provider

@GetMapping("/t3")
public User t3(@RequestParam("name") String name, @RequestParam("age") Integer age){
   User user = new User();
   user.setName(name);
   user.setAge(age);
   return user;
}

 

  • 第二种:换成Post请求

FeignTest.java

@RequestMapping(method = RequestMethod.POST, value = "/t5")
public User t5(User user);

 

eureka-provider

@PostMapping("/t5")
public User t5(@RequestBody User user){
   return user;
}

 

你可能感兴趣的:(SpringCloud)