背景分析
服务消费方基于rest的请求服务提供方的服务时,一种直接的方式就是自己拼接url,拼接参数然后实现服务调用,但每次服务调用都需要这样拼接,打码量复杂且不易维护,此时Feign诞生。
Feign是什么
Feign 是一种声明式Web服务客户端,底层封装了对Rest技术的应用,通过Feign可以简化服务消费方对远程服务提供方法的调用实现。如图所示:
Feign 最早是由 Netflix 公司进行维护的,后来 Netflix 不再对其进行维护,最终 Feign 由社区进行维护,更名为 OpenFeign。
Feign应用实践
1.添加依赖(pom)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在消费者启动类上添加注解
@EnableFeignClients
@SpringBootApplication
public class NacosConsumerApplication {…}
3.定义需要远程调用的API
@FeignClient(name="nacos-provider")//nacos-providers为服务提供者名称
@RestController
interface ConsumerHttpApi{
@GetMapping("/provider/echo/{string}")
public String echoMessage(@PathVariable String string);
}
4.远程调用
@RestController
@RequestMapping("/consumer/feign/")
public class FeignConsumerController {
@Value("${spring.application.name}")
private String appName;
@Autowired
private ConsumerHttpApi consumerHttpApi;
/**基于feign方式的服务调用*/
@GetMapping
public String doFeignEcho(){
return consumerHttpApi.echoMessage(appName);
}
}
5.启动消费者服务,在浏览器中直接通过feign客户端进行访问,如图所示(反复刷新检测其响应结果)