1 服务发现
## 关于服务发现
在微服务架构中,服务发现(Service Discovery)是关键原则之一。手动配置每个客户端或某种形式的约定是很难做的,并且很脆弱。Spring Cloud提供了多种服务发现的实现方式,例如:Eureka、Consul、Zookeeper。
Spring Cloud支持得最好的是Eureka,其次是Consul,最次是Zookeeper。
2、创建一个Maven工程(microservice-discovery-eureka),并在pom.xml中加入如下内容
<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"> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-discovery-eureka</artifactId> <packaging>jar</packaging> <parent> <groupId>com.xujin.study</groupId> <artifactId>microservice-spring-cloud</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies> </project>
3、创建启动类 EurekaApplication
package com.xujin.study; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
4、配置Eureka
server: port: 8761 # 指定该Eureka实例的端口 security: basic: enabled: true user: name: root password: root eureka: instance: hostname: discovery # 指定该Eureka实例的主机名 client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${security.user.name}:${security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
5、启动工程后,访问:[http://127.0.0.1:8761/] 输入你配置的用户名和密码进入Eureka页面
时间: 2024-10-05 07:08:51