provider

引用

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>

配置

  1. spring:
  2. application:
  3. name: provider1
  4. server:
  5. port: 0 # 随机端口
  6. eureka:
  7. client:
  8. service-url:
  9. defaultZone: http://localhost:8761/eureka
  10. instance:
  11. instance-id: ${spring.application.name}:${random.int} # 如果端口随机,则必须设置
  12. prefer-ip-address: true

启动

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. public class ProviderApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(ProviderApplication.class, args);
  6. }
  7. }

提供服务

  1. @RestController
  2. public class ProController {
  3. @RequestMapping("/hello")
  4. public String index(@RequestParam String name) {
  5. return "hello "+name+",this is first messge";
  6. }
  7. }

consumer

1、引用

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.cloud</groupId>
  7. <artifactId>spring-cloud-starter-openfeign</artifactId>
  8. </dependency>

2、配置

  1. spring:
  2. application:
  3. name: comsumer1
  4. server:
  5. port: 8886
  6. eureka:
  7. client:
  8. service-url:
  9. defaultZone: http://localhost:8761/eureka
  10. instance:
  11. prefer-ip-address: true

3、启动

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. @EnableFeignClients
  4. public class ConsumerApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(ConsumerApplication.class, args);
  7. }
  8. }

4、调用provider

必须添加:RequestParam

  1. import org.springframework.cloud.openfeign.FeignClient;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestParam;
  4. @FeignClient("PROVIDER1")
  5. public interface ProviderService {
  6. @GetMapping("/hello")
  7. public String hello(@RequestParam("name") String name);
  8. }

controller正常调用即可:

  1. @RestController
  2. public class ConsumerController {
  3. @Autowired
  4. private ProviderService providerService;
  5. @GetMapping("/hello")
  6. public String hello(String name) {
  7. return providerService.hello(name);
  8. }
  9. }

image.png