首先使用idea建一个空工程,下面涉及到的项目都归属与这个工程
1.注册中心
新建euraka-server项目,导入注册服务端的jar包,pom.xml配置如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
application.yml配置:
server:
port: 8761
spring:
application:
name: eureka-service
eureka:
instance:
hostname: localhost
prefer-ip-address: true
instance-id: ${spring.application.name}(${spring.cloud.client.ip-address}:${server.port})
client:
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
register-with-eureka: false #不将当前项目注册到注册中心
fetch-registry: false #不从注册中心获取注册信息
在Application启动类中添加@EnableEurekaServer标签:
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);
}
}
启动EurekaServerApplication,在页面中访问Enreka:http://localhost:8761
可以看到Eureka的注册管理页面,表示注册中心启动成功。
2.生产者
新建服务提供者(provider-ticket)项目,pom.xml导入eureka客户端和web模块:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application中配置Eureka的注册地址:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8001
spring:
application:
name: provider-ticket
在Application启动类上使用Eureka客户端注解:
@EnableEurekaClient
@SpringBootApplication
public class ProviderTickerApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderTickerApplication.class, args);
}
}
保持注册中心依然运行的情况下,运作这个项目,就可以在注册中心的页面上看到注册项目成功了
做起来难啊,第一次搭建完项目以后,运行ProviderTickerApplication,然后等它去注册的时候就报404,再是一长串的错误信息,说找不到注册中心的服务。最后没办法了,整个项目全部干掉,重新来过才成功的。