1.首先把服务1注册到zookeeper中(zookeeper_不要太随便的博客-CSDN博客)
2.创建服务2
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.yyh</groupId>
<artifactId>cloud.api.commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 80
spring:
application:
name: cloud-order-service
cloud:
zookeeper:
connect-string: 192.168.61.128:2181
启动类
(1)在启动类上使用@EnableFeignClients和@EnableDiscoveryCLient注解
(2)创建service,使用@FeignClient注解来调用服务1的接口,因为在启动类上添加@EnableDiscoveryCLient注解所以服务2也注册进zookeeper中,所以这里的value值代表服务1在zookeeper的名字.
package com.yyh.springcloud.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
@Component
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
@GetMapping("/payment/zk")
String getPaymentById();
}
(3)getPaymentById方法的地址是映射服务1中的接口(下图是服务1的controller)
package com.yyh.springcloud.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
@RequestMapping("/payment")
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@RequestMapping("/zk")
public String paymentzk(){
return "springccloud with zookeeper:"+serverPort+"\t"+ UUID.randomUUID().toString();
}
}
(4)在服务2中创建controller,调用service.
package com.yyh.springcloud.controller;
import com.yyh.bean.R;
import com.yyh.springcloud.service.PaymentFeignService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/consumer/payment/zk")
public String getPaymentById(){
return paymentFeignService.getPaymentById();
}
}
3.启动测试,访问服务2controller中的getPaymentById方法.