provider
引用
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
配置
spring:application:name: provider1server:port: 0 # 随机端口eureka:client:service-url:defaultZone: http://localhost:8761/eurekainstance:instance-id: ${spring.application.name}:${random.int} # 如果端口随机,则必须设置prefer-ip-address: true
启动
@SpringBootApplication@EnableEurekaClientpublic class ProviderApplication {public static void main(String[] args) {SpringApplication.run(ProviderApplication.class, args);}}
提供服务
@RestControllerpublic class ProController {@RequestMapping("/hello")public String index(@RequestParam String name) {return "hello "+name+",this is first messge";}}
consumer
1、引用
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
2、配置
spring:application:name: comsumer1server:port: 8886eureka:client:service-url:defaultZone: http://localhost:8761/eurekainstance:prefer-ip-address: true
3、启动
@SpringBootApplication@EnableEurekaClient@EnableFeignClientspublic class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}}
4、调用provider
必须添加:RequestParam
import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;@FeignClient("PROVIDER1")public interface ProviderService {@GetMapping("/hello")public String hello(@RequestParam("name") String name);}
controller正常调用即可:
@RestControllerpublic class ConsumerController {@Autowiredprivate ProviderService providerService;@GetMapping("/hello")public String hello(String name) {return providerService.hello(name);}}

