package com.sf.remote; import com.sf.dto.UserDto; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; import java.util.Map; // 使用注解@FeignClient 来声明接口对应的服务名 //@LoadBalancerClient(name = "service-provider-demo", // configuration = NacosLoadBalancerConfig.class) @FeignClient("service-provider-demo") public interface MyProviderClient { // 通过一系列的注解配置 可以映射为当前方法对应的远程调用地址为 // http://service-provider-demo/echo/{string} // 此时的入参是方法的入参 返回结果是方法的结果 // String result = restTemplate.getForObject("http://service-provider-demo/echo/{string}", String.class, str); // 本质上 是对restTemplate更上层的封装 // 把远程服务中的接口声明 放在当前接口类中 @GetMapping("/echo/{string}") String echo(@PathVariable("string") String string); // String result = restTemplate.getForObject("http://service-provider-demo/random/{range}", String.class, range); @GetMapping("/random/{range}") String random(@PathVariable("range") int range); @GetMapping("/testParam") String testParam(@RequestParam("param") String param); // 在传递多个参数时 不能直接通过类对象传输 @GetMapping("/testMultiParam") String testMultiParam(UserDto userDto); // 第一种解决方案是 把参数拆解出来 @GetMapping("/testMultiParam") String testMultiParam(@RequestParam("name") String name, @RequestParam("age") Integer age); // 第二种解决方案是 @GetMapping("/testMultiParam") String testMultiParam(@RequestParam Map map); @PostMapping("/postUser") String postUser(@RequestBody UserDto user); // 通过openFeign调用其他微服务时 怎么携带请求头 // 第一种 直接写在方法的注解中 @GetMapping(value = "/token",headers = {"token=123456"}) String token(); // 第二种 方法入参中使用@RequestHeader @GetMapping("/token") String token(@RequestHeader("token") String token); // 第三种 使用Feign拦截器 @GetMapping("/token") String tokenByInterceptor(); }