就是通过注册中心来注册服务于发现,这里是使用eureka注册中心的
下面就是解说代码详细部分:
pom文件的依赖的部分:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--因为eureka使用了hystrix 所以它是必须集成的-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--同时服务中心也是一个client端 所以也是要集成的-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
下面就是对配置文件的详细解说:application.yml
profiles:
#默认是开发环境 可以通过java -jar spring.profiles.active =dev来启动指定环境
active: dev
cloud:
inetutils:
preferred-networks: 127.0.0.1
client:
ip-address: 127.0.0.1
eureka:
server:
peer-node-read-timeout-ms: 3000 #微服务节点连接超时时间
enable-self-preservation: false #是否开启保护,就是是否删除挂掉的服务建议为false
instance:
prefer-ip-address: true # 是否以ip地址注册到中心,如果设置为false的话就是hostname注册
instance-id: ${spring.cloud.client.ip-address}:${server.port} # 注册限制的实例的id
client:
register-with-eureka: true #将服务中心本身注册到进去
fetch-registry: false
healthcheck:
enabled: true
serviceUrl: #默认的注册中心地址
defaultZone: http://127.0.0.1:8082/eureka/
启动类的代码解说:
@SpringCloudApplication
@EnableEurekaServer //注解表示这个类就是一个eureka server中心
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
下面是提供一个client端:
流程也是差不多的一样的pom
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--eureka默认集合了hystrix 所以必须依赖hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--springboot web集合了springmvc所以必须是要依赖webpom-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
下面就是对application.yml的解读:这部分的文件都是包含在上面中的,所以就不做过分的解读了
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8762
spring:
application:
name: eurekaclient
启动类的代码:
@SpringCloudApplication //该注解是默认包含EnableDiscoveryClient 所以是无需显示的声明
public class ApplicationClient {
public static void main(String[] args){
SpringApplication.run(ApplicationClient.class, args);
}
}