使用SpringCloudEureka作为服务注册与发现的中间层,在这里我们要新建两个Maven工程,一个为Eureka-Server作为服务注册中心,一个为Eureka-client作为服务发现.
- 进入https://start.spring.io,新建Eureka-Server工程,添加依赖,选择Generate,将下载的包导入自己的项目路径中
- 同理,新建一个Eureka-client工程,作为客户端服务
- 打开Eureka-Server工程启动类,进行如下操作
package demo.eureka_server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
同时去application.properties中设置
spring.application.name = eureka-server
#Eureka-Server监听端口
server.port=8761
最后一定要记住去pom.xml加上springweb依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 启动服务中心,在浏览器里输入localhost:端口号就可以访问了
- OK,接下来去注册一个客户端服务,这里我们统一都使用web服务,这次打开Eureka-client的启动类,打入注解
package demo.eureka_client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
- 接下来还是去编写application.properties文件,进行如下编写
#euraka-client端口
server.port=8763
#eureka-client应用名称
spring.application.name = eureka-client
#eureka服务器地址
enreka.client.serverUrl.defaultZone = http://localhost:8761/enreka/
- 同理,要记得在pom.xml里打入spring-web依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 启动服务,如果能成功启动,不难发现,我们再观察Eureka-Server服务终端显示了一行很有趣的日志
说明服务注册成功了,这次我们进入localhost:8761,发现确实,服务以及注册成功!
总结:刚开始学习,今天遇到了一个坑弄的我好久,就是Eureka-client的启动类没有打RestController注解,导致服务一直起不来,更完整的博客可参考方志朋的博客