1.创建服务提供者模块
1.1.引入依赖
服务提供者模块不需要导入与feign相关的依赖,只需要按照平常的代码逻辑编写并运行即可,后续可通过服务消费者模块利用feign组件远程调用。
<dependencies>
<!-- nacos-client -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
</dependencies>
1.2.配置文件
spring:
application:
name: cloud-provider
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 # 服务注册中心地址
server:
port: 8001
1.3.启动类
@SpringBootApplication
@EnableDiscoveryClient
public class CloudProviderApplication {
public static void main(String[] args) {
SpringApplication.run(CloudProviderApplication.class, args);
}
}
1.4.编写用于测试的接口
@RestController
public class EchoService {
@RequestMapping("/echo")
public String echo() {
return "This is IndexService index();";
}
}
2.创建服务消费者模块
2.1.引入依赖
主要添加spring-cloud-starter-openfeign
依赖
<dependencies>
<!-- nacos-client -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
</dependencies>
2.2.配置文件
spring:
application:
name: cloud-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
server:
port: 8002
2.3.启动类
需要为启动类加上@EnableFeignClients
注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class CloudConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConsumerApplication.class, args);
}
}
2.4.编写feign接口映射类
该接口用于映射服务提供者模块中对应的接口。其中,feign是按照url路径去查找方法的,并且接口上的方法返回值也需要与提供者相同。注解@FeignClient
中的value值对应服务提供者模块在服务注册中心的应用名。
@FeignClient(value = "cloud-provider")
public interface EchoFeign {
@RequestMapping("/echo")
String echo();
}
2.5.编写用于测试的接口
@RestController
public class EchoController {
@Autowired
private EchoFeign echoFeign;
@RequestMapping("/echo")
public String echo() {
return echoFeign.echo();
}
}
3.开始测试
依次启动服务提供者模块和服务消费者模块,并且访问服务消费者模块对应的测试接口:http://localhost:8002/echo(返回结果如下)