# 从浅入深 学习 SpringCloud 微服务架构(三)注册中心 Eureka(2)

本文主要是介绍# 从浅入深 学习 SpringCloud 微服务架构(三)注册中心 Eureka(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

从浅入深 学习 SpringCloud 微服务架构(三)注册中心 Eureka(2)

段子手168

1、搭建 EurekaServer 注册中心,使用 Eureka 的步骤:

1)搭建 EurekaServer

创建工程,导入依赖坐标,配置 application.yml 文件,配置启动类。

2)将服务提供者注册到 EurekaServer

引入 EurekaClient 的依赖坐标。
修改 application.yml 添加 EurekaServer 的信息。
修改启动类,添加服务发现的支持(可选)。

3)服务消费者通过注册中心获取服务列表,并调用。

Eureka 中的元数据:服务的主机名,IP地址等信息,
可以通过 EurekaServer 进行获取,用于服务之间的调用。

2、在 product_service 服务提供者子工程(子模块)的 pom.xml 文件中引入依赖坐标。


<?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_demo</artifactId><groupId>djh.it</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>product_service</artifactId><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><!--            <version>5.1.32</version>--><version>8.0.26</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- 引入 EurekaClient 依赖坐标 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
</dependencies></project><!-- C:\java-test\idea2019\spring_cloud_demo\product_service\pom.xml -->

3、在 product_service 服务提供者子工程(子模块)的 application.yml 添加 EurekaServer 的信息


## C:\java-test\idea2019\spring_cloud_demo\product_service\src\main\resources\application.ymlserver:port: 9001  # 启动端口 命令行注入。
#  port: ${port:56010}  # 启动端口设置为动态传参,如果未传参数,默认端口为 56010
#  servlet:
#    context-path: /application1spring:application:name: service-product  #spring应用名, # 注意 FeignClient 不支持名字带下划线
#  main:
#    allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。datasource:driver-class-name: com.mysql.jdbc.Driver  # mysql 驱动
#    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: 12311jpa:database: MySQLshow-sql: trueopen-in-view: trueeureka:  # 配置 Eurekaclient:service-url:defaultZone: http://localhost:9000/eureka/instance:prefer-ip-address: true  # 使用 ip 地址注册

4、在 product_service 服务提供者子工程(子模块)中,修改启动类,添加服务发现的支持


/***   C:\java-test\idea2019\spring_cloud_demo\product_service\src\main\java\djh\it\product\ProductApplication.java**   2024-4-17  启动类 ProductApplication.java*/
package djh.it.product;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication
@EntityScan("djh.it.product.domain")
@EnableEurekaClient  //激活 EurekaClient, 同 @EnableDiscoveryClient 注解相同。
public class ProductApplication {public static void main(String[] args) {SpringApplication.run(ProductApplication.class, args);}
}

5、在 product_service 服务提供者子工程(子模块)中,运行启动类,进行测试

浏览器地址栏输入:http://localhost:9000 输出界面如下:

在这里插入图片描述

6、在 order_service 服务消费者子工程(子模块)的 pom.xml 文件中引入依赖坐标。


<?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_demo</artifactId><groupId>djh.it</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>order_service</artifactId><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><!--            <version>5.1.32</version>--><version>8.0.26</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- 引入 EurekaClient 依赖坐标 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency></dependencies></project>
<!-- C:\java-test\idea2019\spring_cloud_demo\order_service\pom.xml -->

7、在 order_service 服务消费者子工程(子模块)的 application.yml 添加 EurekaServer 的信息。


## C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\resources\application.ymlserver:port: 9002  # 启动端口 命令行注入。
#  port: ${port:9002}  # 启动端口设置为动态传参,如果未传参数,默认端口为 9002
#  servlet:
#    context-path: /application1spring:application:name: service-order  #spring应用名, # 注意 FeignClient 不支持名字带下划线
#  main:
#    allow-bean-definition-overriding: true # SpringBoot2.1 需要设定。datasource:driver-class-name: com.mysql.jdbc.Driver  # mysql 驱动
#    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: 12311jpa:database: MySQLshow-sql: trueopen-in-view: trueeureka:  # 配置 Eurekaclient:service-url:defaultZone: http://localhost:9000/eureka/instance:prefer-ip-address: true  # 使用 ip 地址注册

8、在 order_service 服务消费者子工程(子模块),修改启动类,添加服务发现的支持。


/***   C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\java\djh\it\order\OrderApplication.java**   2024-4-19  启动类 OrderApplication.java*/
package djh.it.order;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
@EntityScan("djh.it.order.domain")
@EnableEurekaClient  //激活 EurekaClient, 同 @EnableDiscoveryClient 注解相同。
public class OrderApplication {/***  使用 spring 提供的 RestTemplate 发送 http 请求到商品服务。*      1)创建 RestTemplate 对象交给容器管理。*      2)在使用的时候,调用其方法完成操作(getXX, postXX)。     **/@Beanpublic RestTemplate restTemplate(){return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(OrderApplication.class, args);}
}

9、在 order_service 服务消费者子工程(子模块),

修改 Controller 类,添加 获取服务的元数据信息 。


/***  C:\java-test\idea2019\spring_cloud_demo\order_service\src\main\java\djh\it\order\controller\OrderController.java**  2024-4-19 订单的 controller 类 OrderController.java*/
package djh.it.order.controller;import djh.it.order.domain.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;import java.util.List;@RestController
@RequestMapping("/order")
public class OrderController {// 注入 restTemplate 对象@Autowiredprivate RestTemplate restTemplate;/***  注入 DiscoveryClient : springcloud 提供的获取元数据的工具类。*      调用方法获取服务的元数据信息。*/@Autowiredprivate DiscoveryClient discoveryClient;/***  参数:商品的 id*      通过订单系统,调用商品服务根据id查询商品信息。*          1)需要配置商品对象。*          2)需要调用商品服务。*   可以使用 java 中的 urlconnection, HttpClient, OkHttp 进行远程调用。*   也可以使用 restTemplate 进行远程调用。** @param id* @return*/@RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)public Product findById(@PathVariable Long id){//调用 discoveryClient 方法,已调用服务名称获取所有的元数据。List<ServiceInstance> instances = discoveryClient.getInstances("service-product");for (ServiceInstance instance : instances) {System.out.println(instance);}//获取唯一的一个元数据ServiceInstance instance = instances.get(0);Product product = null;//根据元数据中的主机地址和端口号拼接请求微服务的 URLproduct = restTemplate.getForObject("http://" + instance.getHost() + ":" + instance.getPort() + "/product/1", Product.class);/***  调用商品服务(将微服务的请求路径硬编码到 java 代码中)*  存在问题:对微服务调用的负载均衡,加入API网关,配置的统一管理,链路追踪。*///product = restTemplate.getForObject("http://127.0.0.1:9001/product/1", Product.class);return product;}
}

10、运行 3个 启动类(order_service, product_service, eureka_service),进行测试

在这里插入图片描述

浏览器地址栏输入:http://localhost:9000 输出界面如下:

在这里插入图片描述

浏览器地址栏输入:http://localhost:9001/product/1 输出界面如下:

在这里插入图片描述

浏览器地址栏输入:http://localhost:9002/order/buy/1 输出界面如下:

在这里插入图片描述

上一节学习链接如下:
# 从浅入深 学习 SpringCloud 微服务架构(三)注册中心 Eureka(1)

这篇关于# 从浅入深 学习 SpringCloud 微服务架构(三)注册中心 Eureka(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SpringBoot实现RSA+AES自动接口解密的实战指南

《SpringBoot实现RSA+AES自动接口解密的实战指南》在当今数据泄露频发的网络环境中,接口安全已成为开发者不可忽视的核心议题,RSA+AES混合加密方案因其安全性高、性能优越而被广泛采用,本... 目录一、项目依赖与环境准备1.1 Maven依赖配置1.2 密钥生成与配置二、加密工具类实现2.1

Nginx进行平滑升级的实战指南(不中断服务版本更新)

《Nginx进行平滑升级的实战指南(不中断服务版本更新)》Nginx的平滑升级(也称为热升级)是一种在不停止服务的情况下更新Nginx版本或添加模块的方法,这种升级方式确保了服务的高可用性,避免了因升... 目录一.下载并编译新版Nginx1.下载解压2.编译二.替换可执行文件,并平滑升级1.替换可执行文件

在Java中实现线程之间的数据共享的几种方式总结

《在Java中实现线程之间的数据共享的几种方式总结》在Java中实现线程间数据共享是并发编程的核心需求,但需要谨慎处理同步问题以避免竞态条件,本文通过代码示例给大家介绍了几种主要实现方式及其最佳实践,... 目录1. 共享变量与同步机制2. 轻量级通信机制3. 线程安全容器4. 线程局部变量(ThreadL

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.