【SpringCloud】Eureka的简单使用

2024-06-17 16:28

本文主要是介绍【SpringCloud】Eureka的简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文使用的是jdk17,mysql8。

以下用两个服务做演示:

订单服务:提供订单ID,获取订单详细信息。

商品服务:提供商品ID,获取商品详细信息。

对于上篇http://t.csdnimg.cn/vcWpo  订单服务调用商品服务的时候,使用Spring提供的RestTemplate远程调用时,url部分是写死的,这是很不方便我们后续的操作。针对这个问题,这里使用Eureka来解决。


注册中心

注册中心是一种用于管理和协调微服务架构中各个服务实例的组件。它充当了服务注册和发现的中心,使得微服务能够相互发现和通信

服务注册:每个微服务启动时,会向注册中心注册自己的网络地址、服务名称和其他相关信息。注册中心将这些信息保存起来,以便其他服务可以查询。

服务发现:当一个微服务需要与其他服务进行通信时,它可以向注册中心查询目标服务的信息,如网络地址、可用实例等。这样,服务之间就可以通过注册中心来建立连接,实现相互通信。

注册中心主要有三种角色:

服务提供者(Server):一次业务中,给其他微服务提供接口使用。

服务消费者(Client): 一次业务中,调用其他微服务的接口。

服务注册中心(Registry): 用来保存服务提供者的信息,并且当服务提供者发生变化时,它也同步更新。服务与注册中心使用一定的通信机制,如果服务与注册中心长时间没有通信,那么注册中心就会注销服务。

常见的注册中心:

ZooKeeper:ZooKeeper是一种开源的分布式协调服务,在微服务架构中常被用作注册中心。它具有高可用、一致性和可靠性等特点。(CP保证一致性)节点分为Leader、Follower和Observer,当Leader出现故障时,需要选举出Leader,此时服务不可用。

Eureka:Eureka是Netflix开源的注册中心,具有简单易用、高可用、自我保护等特点,常被用于构建基于Spring Cloud的微服务架构。(AP保证高可用)每个节点都是均等的。

Nacos:Nacos是阿里巴巴开源的一款服务发现和配置管理平台,也可以作为微服务架构中的注册中心。它提供了服务注册、服务发现、动态配置管理和服务治理等功能,对于构建和管理云原生应用非常有用。(CP或AP,默认AP)


CAP理论

CAP理论由下面三部分构成:

一致性(Consistency):多个节点访问数据时,获得的数据都是相同的数据。如果无法保证数据是相同的,就不返回任何数据。

可用性(Availability):每个请求都有响应。可能某个节点返回的结果不对,但是也要返回。

分区容错性(Partition Tolerance):网络分区运行,但是依然可以对外提供服务。如果节点之间出现了故障,也能进行服务。

根据CAP定理,分布式系统只能满足其中两个属性,无法同时满足三个。这是因为在面对网络分区(节点之间无法相互通信)的情况下,系统必须在一致性和可用性之间进行权衡选择。而且在分布式系统中,分区容错性必须考虑,一旦发生错误,导致整个系统不能使用,这是不符合实际的。

于是就出现了:

  • CP架构:保证了分布式系统对外提供的数据一致性。如果不一致,就不返回任何数据。
  • AP架构:保证了分布式系统的可用性,返回的结果就算不对也要返回。

Eureka

Eureka是Netflix OSS套件中的服务注册和发现解决方案。Spring Cloud对Eureka进行了集成,并长期以来作为推荐的解决方案。尽管Eureka 2.0已经停止维护,并且在新的微服务架构设计中不再被推荐使用,但目前仍有许多公司的微服务系统在使用Eureka作为其注册中心。


组成

Eureka Server:作为服务中心的服务端,向微服务应用程序提供服务注册,发现,健康检查等。

Eureka Client:服务提供者,向服务端注册自己的信息(IP, 端口, 服务信息等),服务端会保存信息。


搭建Eureka Server

对于Eureka Server,应该创建成一个独立项目方便管理。这里为了方便,将在上一篇http://t.csdnimg.cn/PV6Xw 的基础上,把Eureka Server创建成子模块。

创建子模块

添加依赖

在刚才的eureka-server模块的pom中添加依赖。

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

完整的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>spring-cloud-eureka</artifactId><groupId>org.example</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>eureka-server</artifactId><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency></dependencies><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

配置文件

server:port: 8360
spring:application:name: eureka-server
eureka:instance:hostname: localhostclient:fetch-registry: false # 表示是否从Eureka Server获取注册信息,默认为true.因为这是一个单点的Eureka Server,不需要同步其他的Eureka Server节点的数据,这里设置为falseregister-with-eureka: false # 表示是否将自己注册到Eureka Server,默认为true.由于当前应用就是Eureka Server,故而设置为false.service-url:# 设置Eureka Server的地址,查询服务和注册服务都需要依赖这个地址defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
logging:pattern:console: '%d{MM-dd HH:mm:ss.SSS} %c %M %L [%thread] %m%n'

启动类

@EnableEurekaServer // 开启 Eureka Server
@SpringBootApplication
public class EurekaServerApplication {public static void main(String[] args) {SpringApplication.run(EurekaServerApplication.class, args);}
}

启动 

至此服务中心搭建成功。


服务注册

把product-service注册。

添加依赖

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

修改配置

主要是添加了

server:port: 8350
spring:application:# 给product-service起个名字,方便eureka管理name: product-servicedatasource:url: jdbc:mysql://82.157.124.63:8220/cloud_product?characterEncoding=utf8&useSSL=falseusername: rootpassword: pxf1212driver-class-name: com.mysql.cj.jdbc.Driver# 设置 Mybatis 的 xml 保存路径
mybatis:configuration: # 配置打印 MyBatis 执行的 SQLlog-impl: org.apache.ibatis.logging.stdout.StdOutImplmap-underscore-to-camel-case: true  #自动驼峰转换# 配置打印 MyBatis 执行的 SQL
logging:file:name: logs/springboot.loglogback:rollingpolicy:max-file-size: 1KBfile-name-pattern: ${LOG_FILE}.%d{yyyy-MM-dd}.%ilevel:com:example:demo: debug# Eureka Client
eureka:client:service-url:# product-service 使用这个地址 注册到 eureka-serverdefaultZone: http://127.0.0.1:8360/eureka/

启动

可以看到已经product-service已经注册到服务中心了。


服务发现

在order-service拉取product-service的服务信息,从而实现服务发现。

添加依赖

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

修改配置

server:port: 8340
spring:application:name: order-servicedatasource:url: jdbc:mysql://82.157.124.63:8220/cloud_order?characterEncoding=utf8&useSSL=falseusername: rootpassword: pxf1212driver-class-name: com.mysql.cj.jdbc.Driver# 设置 Mybatis 的 xml 保存路径
mybatis:configuration: # 配置打印 MyBatis 执行的 SQLlog-impl: org.apache.ibatis.logging.stdout.StdOutImplmap-underscore-to-camel-case: true  #自动驼峰转换# 配置打印 MyBatis 执行的 SQL
logging:file:name: logs/springboot.loglogback:rollingpolicy:max-file-size: 1KBfile-name-pattern: ${LOG_FILE}.%d{yyyy-MM-dd}.%ilevel:com:example:demo: debug
eureka:client:service-url:defaultZone: http://127.0.0.1:8360/eureka

远程调用

从eureka-server中获取product-service中的服务列表,并选择其中的一个调用。

package com.demo.order.service;import com.demo.order.mapper.OrderMapper;
import com.demo.order.model.OrderInfo;
import com.demo.order.model.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaServiceInstance;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import java.util.List;@Slf4j
@Service
public class OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;public OrderInfo selectOrderById(Integer orderId) {OrderInfo orderInfo = orderMapper.selectOrderById(orderId);List<ServiceInstance> instances = discoveryClient.getInstances("product-service");EurekaServiceInstance instance = (EurekaServiceInstance) instances.get(0);log.info(instance.getInstanceId());String url = instance.getUri() + "/product/" + orderInfo.getProductId();ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);orderInfo.setProductInfo(productInfo);return orderInfo;}
}

 

这篇关于【SpringCloud】Eureka的简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1069952

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数