使用RestTemplate
使用Feign
RestTemplate是Spring自己封装的工具,Feign是NetFlix OSS中提供的工具,更方便使用。
第一步:在client-common模块的 pom.xml中添加依赖
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
第二步:定义Feign客户端和使用Feign客户端
package com.demo;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.openfeign.EnableFeignClients;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;/*** @author wujiawei* @see* @since 2021/4/12 下午8:58*/@EnableFeignClients@EnableDiscoveryClient@SpringBootApplicationpublic class AlibabaNacosDiscoveryClientFeignApplication {public static void main(String[] args) {SpringApplication.run(AlibabaNacosDiscoveryClientFeignApplication.class, args);}@FeignClient("alibaba-nacos-discovery-server")interface EchoService{@GetMapping("/echo/{message}")String echo(@PathVariable("message") String message);}@Slf4j@RestControllerstatic class OpenFeignController {@Autowiredprivate EchoService echoService;@GetMapping("feign/echo/{message}")public String feignEcho(@PathVariable String message) {return echoService.echo(message);}}}
- 通过
@EnableFeignClients注解开启扫描Feign客户端的功能 - 通过
interface来定义Feign客户端 - 使用
@FeignClient注解指定接口要调用的服务名称 - 使用Spring MVC的注解如
@GetMapping绑定服务提供方的REST接口
代码示例
- Github:
- Gitee:
