- 创建项目与服务提供者一样。
- 添加依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.5 com.example demo 0.0.1-SNAPSHOT Eureka Consumer Demo Demo project for Spring Boot 1.8 2020.0.4 org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-openfeign org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.apache.maven.plugins maven-resources-plugin 3.1.0 org.springframework.boot spring-boot-maven-plugin
配置资源文件application.properties
#“服务消费者”的名称 spring.application.name=consumer #服务消费者的端口号 server.port=9000 #不注册到服务中心 eureka.client.register-with-eurek=false #服务中心地址 eureka.client.serviceUrl.defaultZone=http://node1:8081/eureka/,http://node2:8082/eureka/,http://node3:8083/eureka/
在启动类中,添加注解以启用客户端的服务注册和发现功能
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
//启用客户端的服务注册和发现功能
@EnableDiscoveryClient
//启用Feign的远程服务调用RPC
@EnableFeignClients
public class EurekaConsumerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerDemoApplication.class, args);
}
}
调用“服务提供者”接口
Feign是一个声明式Web Service客户端,使用Feign能让编写Web Service客户端更加简单,具体步骤为:
- 添加Feign的依赖
- 在启动类中加入注解@EnableFeignClients
- 定义一个接口,在该接口中添加注解以使用它。
package com.example.demo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name="provider")
public interface MmqFeignClient {
@RequestMapping(value = "/hello")
public String hello();
}
实现客户端接口
package com.example.demo.controller;
import com.example.demo.MmqFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConsumerController {
//注入接口
@Autowired
MmqFeignClient mfCli;
@RequestMapping("/hello")
public String index(){
//返回内容
return mfCli.hello();
}
}



