在一个分布式项目中,会出现A服务调用B服务中controller接口的需求,这时我们引入spring cloud来完成这个需求。
如下:demo_server是服务注册,demo_client是服务调用
在父工程中进行依赖版本控制
<dependencyManagement>
<dependencies>
<!--Spring Cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
springboot 与springcloud版本对应可以在官网查到,如下:
nacos服务注册
1.pom坐标导入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2.写入配置文件
application.properties:
server.port=8801
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.application.name=demo-server
3.启动类上加上注解
@EnableDiscoveryClient
4.编写测试controller
@RestController
@CrossOrigin
public class ServerController {
@GetMapping("ServerController")
public String helloServer(){
return "hello server 8801";
}
}
访问nacos查看是否注册成功:
可以观察到服务已经注册成功了,nacos的安装与使用请看nacos入门使用(nacos的安装以及nacos服务注册)
feign服务调用
1.pom导入(注意要把feign和nacos的包都导入)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--服务调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.application.properties:
server.port=8804
spring.application.name=demo-client
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
3.启动类引入注解
@EnableFeignClients
4.写一个接口用于调用远程服务
@FeignClient(name = "demo-server")
@Component
public interface HelloClient {
@GetMapping("ServerController")
public String helloServer();
}
@FeignClient(name = “demo-server”)服务名字
@GetMapping(“ServerController”)这里写访问该接口的路径
5.Controller测试
@RestController
public class ClientController {
@Autowired
private HelloClient helloClient;
@GetMapping("ClientController")
public String HelloClient(){
return helloClient.helloServer();
}
}
运行效果:
访问:http://127.0.0.1:8804/ClientController
帮助到您请点赞关注收藏谢谢!!!