SpringCloud基于SpringBoot,是一系列框架组件的集合,为实现基于微服务的架构设计的。这里简单的使用Spring Cloud Eureka来实现服务治理。
1.在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
2.在springboot工程的启动application类上加@EnableEurekaServer
注解
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
3.在application.yml
配置文件中添加registerWithEureka和fetchRegistry配置信息
rver:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
4.SpringCloudAlibaba基于SpringCloud,服务间调用采用Feign,首先需要新建一个FeignService接口。其@FeignClient注解的值必须为nacos已存在的微服务,容器才能找的到该服务进行调用。其方法申明的注解请求方式和路径,必须跟Controller的对应得上,而Controller里面的该方法还需要加上@inside注解表示可跨服务调用。参数前加上@PathVariable和@RequestBody表示为跨服务http请求,真正的查询其实在Controller里面的该方法。