SpringCloud - Eureka服务注册与发现实战(单节点与集群)

【1】项目基础

首先创建四个工程 :

  • microservicecloud,
  • microservicecloud-api,
  • microservicecloud-consumer-dept-80
  • microservicecloud-provider-dept-8001。

其中microservicecloud作为父工程,其他三个功能均为父工程的Maven Module。microservicecloud-api为公共模块,供其他Module调用使用。

如下图所示:

这里写图片描述

基础工程源码下载:SpringBootMaven分模块实例

【2】创建Eureka服务注册中心(服务端)

① 在父工程microservicecloud右键创建Maven Module–microservicecloud-eureka-7001

这里写图片描述

② pom文件添加依赖

<dependencies>
	<!--eureka-server服务端 -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-eureka-server</artifactId>
	</dependency>
	<!-- 修改后立即生效,热部署 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>springloaded</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
	</dependency>
</dependencies>

③ application.yml

在默认配置下,Eureka Server会将自己也作为客户端来尝试注册自己,我们需要禁用它的客户端禁用行为。

server:
  port: 7001
  
spring:
  application:
    name: microservicecloud-eureka
  
eureka:
  instance:
    hostname: localhost#eureka服务端的实例名称
  client:
    register-with-eureka: false #false 表示不向注册中心注册自己
    fetch-registry: false # false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ 
      #设置与Eureka Server交互的地址 查询服务和注册服务都需要依赖这个地址

④ 主程序添加@EnableEurekaServer注解

@SpringBootApplication
@EnableEurekaServer // EurekaServer服务器端启动类,接受其它微服务注册进来
public class EurekaServer7001_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(EurekaServer7001_App.class, args);
	}
}

启动主程序类,访问http://localhost:7001/ :

这里写图片描述

此时可以看到,在Application下面显示"No instances available",也就是说没有服务被发现—还没有服务注册进Eureka服务注册中心!!!

【3】将服务提供者微服务注册进Eureka

即microservicecloud-provider-dept-8001

① 修改dept工程的pom文件

<!-- 将微服务provider侧注册进eureka -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

② 修改dept工程的application.yml文件

server:
  port: 8001
  
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.web.springcloud.entities    # 所有Entity别名类所在包
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件
    
spring:
   application:
    name: microservicecloud-dept 
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: com.mysql.jdbc.Driver              # mysql驱动包
#    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/clouddb01              # 数据库名称
    username: root
    password: 123456
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: true
    testOnReturn: false
    poolPreparedStatements: true
    #配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

      
eureka:
  client: #客户端注册进eureka服务列表内
    service-url: 
      defaultZone: http://localhost:7001/eureka   
  instance:
    instance-id: microservicecloud-dept8001
    prefer-ip-address: true     #访问路径可以显示IP地址     

③ 主启动类添加@EnableEurekaClient

@SpringBootApplication
@EnableEurekaClient //本服务启动后会自动注册进eureka服务中
public class DeptProvider8001_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptProvider8001_App.class, args);
	}
}

分别启动服务端和客户端,访问Eureka注册中心界面:

这里写图片描述

④ 优化服务注册中心的服务显示

  • 服务名称修改
  • 访问信息有IP提示
eureka:
  client: #客户端注册进eureka服务列表内
    service-url: 
      defaultZone: http://localhost:7001/eureka     
  instance:
    instance-id: microservicecloud-dept8001 # 自定义服务实例Id
    prefer-ip-address: true     # 访问路径可以显示IP地址   

这里写图片描述

优化http://192.168.2.100:8001/info页面显示

默认在服务中心页面点击服务打开http://192.168.2.100:8001/info时显示要么为Error Page 要么为{}。这里修改如下。

总的父工程pom添加构建信息

	<build>
		<finalName>microservicecloud</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<delimiters>
						<delimit>$</delimit>
					</delimiters>
				</configuration>
			</plugin>
		</plugins>
	</build>

使用maven-resources-plugin该插件从src/main/resources路径下解析$作为分隔符的变量的值。

服务提供者application.yml

info: 
  app.name: web-microservicecloud
  company.name: www.web.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

服务提供者添加依赖:

		<!-- actuator监控信息完善 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

此时再次访问http://192.168.2.100:8001/info:

这里写图片描述

【4】服务发现 DiscoveryClient

① 代码修改

对于注册进Eureka里面的微服务,可以通过服务发现来获得该服务的信息。

主程序类添加@EnableDiscoveryClient进行服务发现:

@SpringBootApplication
@EnableEurekaClient //本服务启动后会自动注册进eureka服务中
@EnableDiscoveryClient //服务发现--该注解可以省略
public class DeptProvider8001_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptProvider8001_App.class, args);
	}
}

DeptController修改如下:

@Autowired
private DiscoveryClient client;

//对外暴露服务信息接口,供外部查询注册中心的微服务进行调用
@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
public Object discovery()
{
	List<String> list = client.getServices();
	System.out.println("**********" + list);

	List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");
	for (ServiceInstance element : srvList) {
		System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
				+ element.getUri());
	}
	return this.client;
}

分别启动服务中心7001和服务提供者8001,浏览器访问http://localhost:8001/dept/discovery:

这里写图片描述

② @EnableDiscoveryClient 与 @EnableEurekaClient区别

首先 @EnableEurekaClient@EnableDiscoveryClient都是Spring Cloud中用于启用服务注册与发现的注解。也就是说二者之一任何注解都可以实现发现注册中心并将服务注册上去的功能。

其次在低版本中@EnableEurekaClient 注解自动添加了@EnableDiscoveryClient。如下所示,该注解的应用前提是注册中心为Eureka。


/**
 * Convenience annotation for clients to enable Eureka discovery configuration
 * (specifically). Use this (optionally) in case you want discovery and know for sure that
 * it is Eureka you want. All it does is turn on discovery and let the autoconfiguration
 * find the eureka classes if they are available (i.e. you need Eureka on the classpath as
 * well).
 *
 * @author Dave Syer
 * @author Spencer Gibb
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@EnableDiscoveryClient
public @interface EnableEurekaClient {

}

分界版本是Dalston。在Dalston之后的版本中(不含Dalston),在spring-cloud-netflix-eureka-client-2.2.5.RELEASE中,去掉了@EnableDiscoveryClient注解。

/**
 * Convenience annotation for clients to enable Eureka discovery configuration
 * (specifically). Use this (optionally) in case you want discovery and know for sure that
 * it is Eureka you want. All it does is turn on discovery and let the autoconfiguration
 * find the eureka classes if they are available (i.e. you need Eureka on the classpath as
 * well).
 *
 * @author Dave Syer
 * @author Spencer Gibb
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface EnableEurekaClient {

}

在spring-cloud-commons-2.2.5.RELEASE中,@EnableDiscoveryClient注解如下所示:

/**
 * Annotation to enable a DiscoveryClient implementation.
 * @author Spencer Gibb
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(EnableDiscoveryClientImportSelector.class)
public @interface EnableDiscoveryClient {

	/**
	 * If true, the ServiceRegistry will automatically register the local server.
	 * @return - {@code true} if you want to automatically register.
	 */
	boolean autoRegister() default true;

}

从二者分属不同包也可以看出EnableEurekaClient 只是针对于eureka注册中心,而EnableDiscoveryClient 属于springcloud commons组件,可以与Eureka、Consul等多种注册中心对接。

其实在Dalston之后的版本中(不含Dalston),如下所示在eureka-client包的spring.factories中可以看到一系列配置类EnableAutoConfiguration,其中就有EurekaDiscoveryClientConfiguration。也就是说,在这些版本中,只要启动了springboot自动配置,那么无需配置EnableEurekaClient 或者EnableDiscoveryClient 注解。
在这里插入图片描述

【5】服务消费者发现服务并进行调用

即microservicecloud-consumer-dept-80。

① 修改application.yml文件

server:
  port: 80

spring:
  application:
    name: microservicecloud-consumer
  
eureka:
  instance:
    prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  client:
#    register-with-eureka: false # 不向服务注册中心注册自己
    service-url: 
      defaultZone: http://localhost:7001/eureka/

② 修改自定义配置类ConfigBean

@Configuration
public class ConfigBean {
	
	@LoadBalanced//开启负载均衡机制
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate(); // 用来进行HTTP通信
    }

}

③ 修改主程序类

@SpringBootApplication
@EnableDiscoveryClient //服务发现
public class DeptConsumer80_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptConsumer80_App.class, args);
	}
}

④ 修改DeptController_Consumer

这里写图片描述

分别启动服务注册中心、服务提供者和服务消费者,分别测试界面如下:

这里写图片描述
这里写图片描述

这里有个小坑,在配置类中注册RestTemplate需要添加@LoadBalanced注解,否则在消费者使用服务名调用服务提供者时,会报java.net.UnknownHostException异常。

RestTemplate只是类似于httpclient的一个发送rest风格的请求,它这里是没有办法去识别所谓的服务名的,不识别服务名当然就会报那个错误咯。在《spring Cloud 微服务实战》这本书上写的,一定要@LoadBalanced注解修饰的restTemplate才能实现服务名的调用,没有修饰的restTemplate是没有该功能的。@LoadBalanced是Netflix的ribbon中的一个负载均衡的注解,当项目加了@LoadBalanced的时候,就可以了。

@LoadBalanced该注解源码如下:


/**
 * Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient
 * @author Spencer Gibb
 */
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface LoadBalanced {
}

@LoadBalanced这个注解加上之后,这个注解有3件事情要处理。

第一件就是从负载均衡器中选一个对应的服务实例,那为什么从负载均衡器中挑选,原因很明显就是,所有的服务名实例都放在负载均衡器中的serverlist。

第二件事情就是从第一件事情挑选的实例中去请求内容。

第三件事情就是由服务名转为真正使用的ip地址。

【6】服务集群

单个服务中心是不可靠的,需要多个服务中心来确保Eureka的高可用性。

① 创建多个注册中心

按照microservicecloud-eureka-7001创建microservicecloud-eureka-7002和microservicecloud-eureka-7003

这里写图片描述

② 域名映射

如下所示,如果每个eureka.server.instance.name都为localhost,是很麻烦的一件事。

eureka:
  instance:
    hostname: localhost # eureka服务端的实例名称

这里是Win10系统,在C:\Windows\System32\drivers\etc修改hosts文件:

# spring cloud eureka
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com

③ 修改服务中心yml

7001yml

server:
  port: 7001
  
spring:
  application:
    name: microservicecloud-eureka7001
  
eureka:
  instance:
    hostname: eureka7001.com # eureka服务端的实例名称
  client:
    register-with-eureka: false #false 表示不向注册中心注册自己
    fetch-registry: false # false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
#      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #设置与Eureka Server交互的地址 查询服务和注册服务都需要依赖这个地址
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

7002 yml

server:
  port: 7002
  
spring:
  application:
    name: microservicecloud-eureka7002
  
eureka:
  instance:
    hostname: eureka7002.com # eureka服务端的实例名称
  client:
    register-with-eureka: false #false 表示不向注册中心注册自己
    fetch-registry: false # false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
#      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #设置与Eureka Server交互的地址 查询服务和注册服务都需要依赖这个地址
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/

7003 yml

server:
  port: 7003
  
spring:
  application:
    name: microservicecloud-eureka7003
  
eureka:
  instance:
    hostname: eureka7003.com # eureka服务端的实例名称
  client:
    register-with-eureka: false #false 表示不向注册中心注册自己
    fetch-registry: false # false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
#      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #设置与Eureka Server交互的地址 查询服务和注册服务都需要依赖这个地址
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7001.com:7001/eureka/

④ 修改服务提供者yml

eureka:
  client: #客户端注册进eureka服务列表内
   #表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用 负载均衡
    fetch-registry: true
    service-url: 
#      defaultZone: http://localhost:7001/eureka/
       defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/      
  instance:
    instance-id: microservicecloud-dept8001 # 自定义服务实例Id
    prefer-ip-address: true     #访问路径可以显示IP地址    

⑤ 修改服务消费者yml

server:
  port: 80

spring:
  application:
    name: microservicecloud-consumer
  
eureka:
  instance:
    prefer-ip-address: true # 注册服务的时候使用服务的ip地址
  client:
   #表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用 负载均衡
    fetch-registry: true
    service-url: 
#      defaultZone: http://localhost:7001/eureka/
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  

分别启动服务中心7001、7002、7003,服务提供者和服务消费者,测试如下图:

这里写图片描述

这里写图片描述
这里写图片描述

【7】集群中的小坑unavailable-replicas

如下图所示:

这里写图片描述

可怕不,虽然还有两个服务中心,但是都在unavailable-replicas中!!!

这里需要注意的是Eureka服务注册与发现中讲的Eureka服务高可用性—Eureka Server的高可用实际上就是将自己做为服务向其他服务注册中心注册自己,这样就可以形成一组互相注册的服务注册中心,以实现服务清单的互相同步,达到高可用的效果。

也就是说需要把自己(服务中心)作为服务注册到另外的服务中心中!!!

还有一点需要注意的是三个服务中心应用名字应保持一致!!!

修改三个服务中心的配置文件(这里以7001示例):

server:
  port: 7001
  
spring:
  application:
    name: microservicecloud-eureka
  
eureka:
  instance:
    hostname: eureka7001.com # eureka服务端的实例名称
  client:
    register-with-eureka: true #false 表示不向注册中心注册自己
    fetch-registry: false # false 表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

此时再次访问服务中心页面:

这里写图片描述

【8】Eureka2.X的引入

1.X 引入如下:

	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-eureka-server</artifactId>
	</dependency>

在2.X版本中,依赖分为了客户端和服务端。

	<!--eureka-server服务端 -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
	</dependency>

	<!--eureka-server客户端 -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	</dependency>

本篇博文项目地址:https://github.com/JanusJ/SpringCloud/

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值