我们现在的服务还是比较少,服务管理起来也是比较简单的。如果我们有几十个、几百个微服务话这样话会比较麻烦,那就需要进行微服务的管理和自理了。那什么是服务自理呢?
SpringCloud 封装了Netflix公司开发的Eureka 来进行微服务自理,在传统的rpc 调用框架中,管理每个服务于服务之间依赖关系比复杂,管理起来比较麻烦。所以需要使用服务自理,管理服务与服务之间的依赖关系,可以实现服务调用、负载均衡、服务短路、服务容错和服务自动发现与注册。
接下来,我们需要进行Eureka进行项目的整合了。
新建Module
修改pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>pcloud</artifactId>
<groupId>com.younger.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>pcloud-eureka-server6001</artifactId>
<dependencies>
<!--eureka-server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--boot web actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--一般通用配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>
Eureka 1.x 和 2.x 引入也是存在差异性的:
以前老版本
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
现在新版本
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
配置application.yml文件
server:
port: 6001
eureka:
instance:
hostname: localhost
client:
#false表示不向注册中心注册自己。
register-with-eureka: false
# 不需要其他服务拉取服务
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
编写启动类 EurekaMain6001
package com.younger.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaMain6001 {
public static void main(String[] args) {
SpringApplication.run(EurekaMain6001.class, args);
}
}
启动项目
测试: http://localhost:6001/