探索 Spring Cloud:微服务架构的强大引擎

Spring Cloud 是一个用于构建分布式系统的开源框架,它基于 Spring Boot 提供了一系列工具和组件,帮助开发者快速构建微服务架构。以下是对 Spring Cloud 微服务的介绍,并结合代码示例进行说明。

一、核心组件

1、服务注册与发现(Eureka)

在微服务架构中,服务注册与发现是一个关键组件。Spring Cloud Eureka 提供了服务注册中心和服务发现的功能。

1.1、创建服务注册中心(Eureka Server):
  • 创建一个 Spring Boot 项目作为服务注册中心,添加 spring-cloud-starter-netflix-eureka-server 依赖。
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
   </dependency>
  • 在主类上添加 @EnableEurekaServer 注解,启用服务注册中心功能。
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

   @SpringBootApplication
   @EnableEurekaServer
   public class EurekaServerApplication {
       public static void main(String[] args) {
           SpringApplication.run(EurekaServerApplication.class, args);
       }
   }
  • 在 application.properties 配置文件中设置服务注册中心的端口和其他属性。
   server.port=8761
   eureka.client.register-with-eureka=false
   eureka.client.fetch-registry=false
1.2、服务注册:
  • 在微服务项目中添加 spring-cloud-starter-netflix-eureka-client 依赖。
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
   </dependency>
  • 在微服务的 application.properties 配置文件中设置服务注册中心的地址和微服务的名称等属性。
   server.port=8080
   spring.application.name=your-service-name
   eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
  • 在微服务的主类上添加 @EnableDiscoveryClient 注解,启用服务发现功能。
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

   @SpringBootApplication
   @EnableDiscoveryClient
   public class YourServiceApplication {
       public static void main(String[] args) {
           SpringApplication.run(YourServiceApplication.class, args);
       }
   }

在这个示例中,我们创建了一个 Spring Boot 应用,并使用 @EnableEurekaServer 注解启用 Eureka 服务注册中心。

2、负载均衡(Ribbon)

Ribbon 是一个客户端负载均衡工具,它与 Eureka 集成,实现了对服务提供者的负载均衡调用。

2.1、添加依赖
  • 在微服务项目中添加 spring-cloud-starter-netflix-ribbon 依赖。
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
   </dependency>
2.2、配置RestTemplate 
  • 使用 @LoadBalanced 注解标注 RestTemplate,使其具备负载均衡的能力。
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.client.loadbalancer.LoadBalanced;
   import org.springframework.context.annotation.Bean;
   import org.springframework.web.client.RestTemplate;

   @SpringBootApplication
   public class YourServiceApplication {
       public static void main(String[] args) {
           SpringApplication.run(YourServiceApplication.class, args);
       }

       @Bean
       @LoadBalanced
       public RestTemplate restTemplate() {
           return new RestTemplate();
       }
   }
2.3、调用服务

使用负载均衡的 RestTemplate 调用服务提供者。

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.boot.CommandLineRunner;
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.web.client.RestTemplate;

   @SpringBootApplication
   public class YourServiceApplication implements CommandLineRunner {
       @Autowired
       private RestTemplate restTemplate;

       public static void main(String[] args) {
           SpringApplication.run(YourServiceApplication.class, args);
       }

       @Override
       public void run(String... args) throws Exception {
           String response = restTemplate.getForObject("http://your-service-name/your-endpoint", String.class);
           System.out.println(response);
       }
   }

3、断路器(Hystrix)

Hystrix 是一个用于处理分布式系统延迟和容错的库,它通过断路器模式来防止故障扩散。

3.1、添加依赖
  • 在微服务项目中添加 spring-cloud-starter-netflix-hystrix 依赖。
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
   </dependency>

使用 @EnableCircuitBreaker 注解启用 Hystrix。

3.2、启动断路器
  • 在微服务的主类上添加 @EnableCircuitBreaker 注解,启用断路器功能
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;

   @SpringBootApplication
   @EnableCircuitBreaker
   public class YourServiceApplication {
       public static void main(String[] args) {
           SpringApplication.run(YourServiceApplication.class, args);
       }
   }
3.3、实现断路器功能
  • 使用 @HystrixCommand 注解标注方法,实现断路器功能
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.boot.CommandLineRunner;
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
   import org.springframework.web.client.RestTemplate;

   @SpringBootApplication
   public class YourServiceApplication implements CommandLineRunner {
       @Autowired
       private RestTemplate restTemplate;
       @Autowired
       private CircuitBreakerFactory circuitBreakerFactory;

       public static void main(String[] args) {
           SpringApplication.run(YourServiceApplication.class, args);
       }

       @Override
       public void run(String... args) throws Exception {
           String response = circuitBreakerFactory.create("hystrixCommand").run(() -> restTemplate.getForObject("http://your-service-name/your-endpoint", String.class),
                   throwable -> "fallback response");
           System.out.println(response);
       }
   }

4、网关(Zuul)

Zuul 是一个微服务网关,它提供了路由、过滤和安全等功能。

4.1、创建 Zuul 网关:
  • 创建一个 Spring Boot 项目作为网关服务,添加 spring-cloud-starter-netflix-zuul 依赖
   zuul.routes.your-service.path=/your-service/**
   zuul.routes.your-service.url=http://localhost:8080

在网关服务的主类上添加 @EnableZuulProxy 注解,启用网关功能

   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

   @SpringBootApplication
   @EnableZuulProxy
   public class ZuulGatewayApplication {
       public static void main(String[] args) {
           SpringApplication.run(ZuulGatewayApplication.class, args);
       }
   }
4.2、配置路由:
  • 在网关服务的 application.properties 配置文件中配置路由规则。
   zuul.routes.your-service.path=/your-service/**
   zuul.routes.your-service.url=http://localhost:8080

在这个示例中,我们配置了一个路由,将所有以 /service-provider/ 开头的请求转发到名为 service-provider 的服务。

5、配置中心(Spring Cloud Config)

Spring Cloud Config 提供了集中式的配置管理功能,可以将微服务的配置文件集中存储和管理。

5.1、创建配置服务器
  1. 创建一个 Spring Boot 项目作为配置中心服务
  2. 添加 spring-cloud-config-server 依赖。
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-config-server</artifactId>
   </dependency>
5.2、启用配置中心
  • 在配置中心服务的主类上添加 @EnableConfigServer 注解,启用配置中心功能。
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.cloud.config.server.EnableConfigServer;

   @SpringBootApplication
   @EnableConfigServer
   public class ConfigServerApplication {
       public static void main(String[] args) {
           SpringApplication.run(ConfigServerApplication.class, args);
       }
   }
5.3、配置中心服务
  • 在配置中心服务的 application.properties 配置文件中设置配置文件的存储位置和其他属性,可以是 Git 仓库、本地文件系统等。
   server.port=8888
   spring.cloud.config.server.git.uri=https://github.com/your-text/your.git
   spring.cloud.config.server.git.search-paths=config-repo
5.4、创建服务客户端
  • 在微服务项目中添加 spring-cloud-starter-config 依赖。
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-config</artifactId>
   </dependency>
  • 在微服务项目的 application.properties 配置文件中设置配置中心的地址和微服务的名称等属性
   server.port=8080
   spring.application.name=your-name
   spring.cloud.config.uri=http://localhost:8888 // 配置服务器地址
  • 在微服务项目中,可以通过 @Value 注解注入配置属性。
   import org.springframework.beans.factory.annotation.Value;
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.web.bind.annotation.GetMapping;
   import org.springframework.web.bind.annotation.RestController;

   @SpringBootApplication
   @RestController
   public class YourServiceApplication {

       @Value("${your.property.key}")
       private String yourProperty;

       @GetMapping("/your-endpoint")
       public String getPropertyValue() {
           return yourProperty;
       }

       public static void main(String[] args) {
           SpringApplication.run(YourServiceApplication.class, args);
       }
   }
5.5、动态刷新配置

  • 如果需要实现配置的动态刷新,可以在服务项目中添加 spring-boot-starter-actuator 依赖,并开启 /refresh 端点。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • 在服务项目中,可以使用 @RefreshScope 注解标记需要动态刷新的类或方法。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RefreshScope
@RestController
public class YourServiceController {

    @Value("${your.property.key}")
    private String yourProperty;

    @GetMapping("/your-endpoint")
    public String getPropertyValue() {
        return yourProperty;
    }
}

当配置发生变化时,可以通过发送 POST 请求到 /actuator/refresh 端点来触发服务项目的配置刷新。

二、微服务架构优势

  1. 独立性和可扩展性:每个微服务可以独立开发、部署和扩展,不同服务之间通过轻量级的通信机制(如 RESTful API)进行交互。这使得系统可以根据业务需求快速迭代和扩展,而不会影响其他部分。

  2. 技术多样性:不同的微服务可以使用不同的编程语言和技术栈,充分发挥各种技术的优势。例如,一个服务可以使用 Java,另一个服务可以使用 Python 或 Node.js。

  3. 高可用性:由于每个微服务都是独立的,一个服务的故障不会影响整个系统。可以通过部署多个实例、使用负载均衡和断路器等机制来提高系统的可用性。

  4. 易于维护:微服务架构将复杂的系统拆分成小的、易于理解和维护的模块。开发团队可以专注于特定的服务,提高开发效率和代码质量。

三、开发流程

  1. 服务划分:根据业务需求将系统划分为多个微服务,每个服务负责特定的业务功能。确定服务的边界、接口和数据模型。

  2. 服务开发:使用 Spring Boot 开发每个微服务,实现业务逻辑、数据库访问、对外接口等。可以使用各种技术和框架来满足服务的特定需求。

  3. 服务注册与发现:将服务注册到服务注册中心,以便其他服务能够发现和调用。配置服务的名称、端口号、健康检查等信息。

  4. 服务间通信:使用 RESTful API、消息队列等方式实现服务间的通信。确保通信的可靠性、安全性和性能。

  5. 配置管理:使用配置中心集中管理微服务的配置文件,实现配置的动态更新。将配置信息与代码分离,提高可维护性。

  6. 监控和日志:使用监控工具(如 Prometheus、Grafana)和日志管理工具(如 ELK Stack)对微服务进行监控和日志收集,及时发现和解决问题。

  7. 部署和运维:使用容器化技术(如 Docker、Kubernetes)对微服务进行部署和运维,提高部署效率和系统的可扩展性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/899917.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

java实现redis的消息发送和消费,类似kafka功能

确保在 pom.xml 中添加了 Spring Data Redis 和 Jedis 的依赖。如下所示&#xff1a;<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency&g…

C数组与字符串

1.数组 数组是一组有序的、类型相同的数据的集合&#xff0c;这些数据被称为数组的元素。 每个数组都有一个名字&#xff0c;我们称之为数组名。 数组名代表数组的起始地址。 数组元素由索引或下标标识&#xff0c;索引或下标从0开始 数组的特性必须在使用前定义&#xff1…

Mycat 详细介绍及入门实战,解决数据库性能问题

一、基本原理 1、数据分片 &#xff08;1&#xff09;、水平分片 Mycat 将一个大表的数据按照一定的规则拆分成多个小表&#xff0c;分布在不同的数据库节点上。例如&#xff0c;可以根据某个字段的值进行哈希取模&#xff0c;将数据均匀的分布到不同的节点上。 这样做的好处…

OpenIPC开源FPV之Ardupilot配置

OpenIPC开源FPV之Ardupilot配置 1. 源由2. 问题3. 分析3.1 MAVLINK_MSG_ID_RAW_IMU3.2 MAVLINK_MSG_ID_SYS_STATUS3.3 MAVLINK_MSG_ID_BATTERY_STATUS3.4 MAVLINK_MSG_ID_RC_CHANNELS_RAW3.5 MAVLINK_MSG_ID_GPS_RAW_INT3.6 MAVLINK_MSG_ID_VFR_HUD3.7 MAVLINK_MSG_ID_GLOBAL_P…

ActiveMQ消息模式Queue和Topic机制讲解

Docker安装ActiveMQ镜像以及通过Java生产消费activemq示例_docker activemq-CSDN博客 背景 周末由于服务器异常宕机&#xff0c;导致业务系统重启后出现ActiveMQ中的数据没有被正常消费&#xff0c;运维认为是消息积压&#xff0c;便联系博主排查。 最终发现并不存在消息积压…

GIS常见前端开发框架

#1024程序员节&#xff5c;征文# 伴随GIS的发展&#xff0c;陆续出现了众多开源地图框架&#xff0c;这些地图框架与众多行业应用融合&#xff0c;极大地拓展了GIS的生命力&#xff0c;这里介绍几个常见的GIS前端开发框架&#xff0c;排名不分先后。 1.Leaflet https://leafl…

Spring--1

spring是一个轻量级的&#xff0c;采用IOC与AOP编程思想的java后端开发框架&#xff0c;简化了企业级的应用开发。 Spring体系 数据访问层&#xff0c;Web层&#xff0c;配置中心&#xff0c;测试区 IOC 控制反转&#xff0c;将创建对象的控制权交由Spring框架&#xff0c;需…

Tongweb7049m4+THS6010-6012版本 传真实ip到后端(by yjm+lwq)

遇到客户需要通过ths传真实ip到后端也就是部署到tongweb的需求&#xff0c;在ths的httpserver.conf里的location块配置了以下内容&#xff1a; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwar…

Redis技术解析(基于Redis的项目实战)

本项目源码请从作者仓库中拉取 Redis复盘: 本项目将通过实战讲解Redis的应用&#xff0c;包括使用Redis共享session实现短信登录、处理商户查询缓存问题、进行优惠券秒杀活动、基于GEOHash定位附近商户、实现UV统计、管理用户签到、构建好友关注系统&#xff0c;以及使用List和…

数字后端实现静态时序分析STA Timing Signoff之min period violation

今天给大家分享一个在高性能数字IC后端实现timing signoff阶段经常遇到的min period violation。大部分时候出现memory min period问题基本上都是需要返工重新生成memory的。这是非常致命的错误&#xff0c;希望大家在做静态时序分析时一定要查看min period violation。 什么是…

Oracle 常见索引扫描方式概述,哪种索引扫描最快!

一.常见的索引扫描方式 INDEX RANGE SCANINDEX FAST FULL SCANINDEX FULL SCAN(MIN/MAX)INDEX FULL SCAN 二.分别模拟使用这些索引的场景 1.INDEX RANGE SCAN create table t1 as select rownum as id, rownum/2 as id2 from dual connect by level<500000; create inde…

Unity RPG梦幻场景素材(附下载链接)

Unity RPG梦幻场景素材 点击下载资源 效果图&#xff1a; 资源链接

CORS预检请求配置流程图 srpingboot和uniapp

首先要会判断预检请求 还是简单请求 简单请求 预检请求 #mermaid-svg-1R9nYRa7P9Pll4AK {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-1R9nYRa7P9Pll4AK .error-icon{fill:#552222;}#mermaid-svg-1R9nYRa7P9Pll4…

geoserver解析元数据获取图层相关参数

需求&#xff1a; 1、通过geoserver地址获取所有图层名称&#xff1b; 2、加载wms服务&#xff0c;实现自动定位。 获取图层名和范围视图有两种思路&#xff1a; 1、调取geoserver的rest接口。缺点就是需要验证登录。 rest接口官方文档&#xff1a;GeoServer API Docs 2、…

C++(标准输入输出流、命名空间、string字符串、引用)

C特点及优势 &#xff08;1&#xff09;实现了面向对象&#xff0c;在高级语言中&#xff0c;处理运行速度是最快&#xff1b; &#xff08;2&#xff09;非常灵活&#xff0c;功能非常强大&#xff0c;相对于C的指针优势&#xff0c;C的优势为性能和类层次结构&#x…

书生营 L0G4000 玩转HF/魔搭/魔乐社区

模型下载 在codespace上给环境装包&#xff0c;按照教材即可 运行后下载成功 建立下载json文件 新建下载internlm2_5-chat-1_8b的json文件 运行结果 基本上没啥问题&#xff0c;照着教程来就行 模型上传&#xff08;可选&#xff09; push的时候需要先认证token 最后的…

人工智能+医学

医学影响的内型&#xff1a;(X光片、计算机断层扫描、磁共振成像、超声波&#xff09; ITK snap医学图像读取 医学影像领域常见任务: 图像分类、语义分割、疾病预测、目标检测、图像配准、图像生成(应用少)、图像增强、生成放射学报告。 需要有很强的可解释…

Xshell上Linux的基础指令

目录 1、Xshell的使用 2、Linux的常用命令 2.1 位置跳转命令 1、ls 2、cd 3、pwd 2.2 文件操作 1、touch 2、cat 3、echo 4、vim 2.3 目录操作 1、mkdir 2、rm 2.4 移动操作 1、mv 2、cp 2.5 命令手册 2.6 查找操作 2.7 进程展示 2.8 网络信息 3、搭建w…

JS | 详解图片懒加载的6种实现方案

目录 一、什么是懒加载&#xff1f; 二、为什么要懒加载&#xff1f; 三、图片懒加载的实现原理 四、图片懒加载实现方式 3.1 方案一&#xff1a;设置 img 标签属性 loading“lazy” 3.2 方案二&#xff1a;利用JS监听scroll滚动事件 3.3 方案三&#xff1a;利用元素的…

Aatrox-Bert-VITS2部署指南

一、模型介绍 【AI 剑魔 ①】在线语音合成&#xff08;Bert-Vits2&#xff09;&#xff0c;将输入文字转化成暗裔剑魔亚托克斯音色的音频输出。 作者&#xff1a;Xz 乔希 https://space.bilibili.com/5859321 声音归属&#xff1a;Riot Games《英雄联盟》暗裔剑魔亚托克斯 …