亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Spring Cloud 微服務學習入門:從零開始的實戰指南

標簽:
雜七雜八
概述

学习Spring Cloud微服务入门,探索微服务基础概念,包括独立部署、自主定位、服务间通信等,以及如何使用Spring Cloud简化分布式系统构建。从Hello World微服务开始,集成Eureka、Spring Cloud Gateway等工具,实现服务发现与配置管理,构建具备弹性与高可用性的微服务架构,并通过案例学习异步消息处理、微服务安全等关键实践。

微服务基础概念

微服务是一种将复杂系统分解为多个独立、可部署、松耦合服务的架构风格。这种架构鼓励高度可伸缩且易于维护的系统设计。与传统的单体架构相比,微服务架构允许团队以更快的速度进行迭代和部署,并且可以独立地将特定业务功能部署到生产环境。

微服务特点

  • 独立部署:每个微服务都是一个独立的实体,可以独立开发、构建和部署。
  • 自主定位:每个微服务有自己的数据存储,不需要与其它服务共享数据库。
  • 极小粒度:服务通常专注于单一功能,使得代码更容易理解和维护。
  • 服务间通信:服务之间通过轻量级机制(如HTTP API)进行交互,而不是共享内存或直接调用方法。
  • 弹性:单独的服务可以独立地进行伸缩,根据负载调整资源使用。
  • 故障隔离:一个服务的失败不会影响其他服务,提高了系统的稳定性和可靠性。
微服务与传统单体架构对比

在微服务架构中,应用被分解成多个独立的服务,每个服务负责特定的业务功能。相比之下,传统单体架构将所有功能集成在一个大型进程中,一旦某个部分出现问题,就可能影响整个应用的可用性。

// 示例:微服务架构中的单一服务
public class OrderService {
    public void createOrder(OrderRequest request) {
        // 创建订单的逻辑
    }
}

// 传统单体架构示例
public class ShoppingCartApp {
    public void addProduct(Product product) {
        // 将产品添加到购物车的逻辑
    }

    public void checkout() {
        // 结账的逻辑
    }
}
Spring Cloud 概览

Spring Cloud 是一个基于Spring Boot的工具集,用于简化分布式系统中微服务的构建。它提供了一系列组件和工具,如服务注册与发现、配置管理、断路器、负载均衡等,使开发者可以轻松地构建、测试和部署微服务。

Spring Cloud 功能模块及用途

  • Spring Cloud Netflix:核心组件,提供服务发现、负载均衡、断路器等功能。
  • Spring Cloud Config:用于集中管理应用程序的配置。
  • Spring Cloud Gateway:构建统一入口,实现路由、过滤等功能。
  • Spring Cloud OpenFeign:用于编写服务接口的更友好、更简洁的客户端代码。
  • Spring Cloud Sleuth:提供分布式日志追踪功能。
  • Spring Cloud Zuul:虽然已被 Spring Cloud Gateway 替代,但仍然用于更复杂的路由和过滤。

Spring Cloud 整合与配置

在开始构建微服务前,需要为项目添加Spring Cloud的依赖。例如,为了集成Eureka服务注册与发现,我们可以在pom.xml中添加如下配置:

<dependencies>
    <!-- Spring Cloud Starter Eureka Client -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!-- 其他Spring Cloud依赖 -->
    <!-- ... -->
</dependencies>

接下来,配置Eureka客户端,以告知系统连接到哪个Eureka服务器:

spring:
  application:
    name: my-service-instance
  cloud:
    discovery:
      enabled: true
      instance:
        hostname: localhost
        ip-address: 127.0.0.1
      registry:
        host: localhost
        port: 8761
构建第一个微服务

从Hello World开始

创建一个简单的“Hello World”微服务作为起点,这将帮助我们熟悉如何使用Spring Boot构建微服务的基本流程。

创建项目

使用Maven或Gradle创建一个新的Spring Boot项目。

添加依赖

pom.xml中添加Spring Web依赖:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

编写代码

src/main/java目录下创建一个名为HelloController.java的文件,并添加以下代码:

package com.example.demo.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public ResponseEntity<String> greeting() {
        return ResponseEntity.ok("Hello World!");
    }
}

运行服务

使用Maven或Gradle运行项目。可以通过浏览器访问http://localhost:8080/hello,应看到“Hello World!”响应。

使用Spring Boot快速创建微服务

构建微服务时,Spring Boot 提供了快速启动应用的便捷功能。例如,可以通过以下命令创建一个简单的微服务:

mvn spring-boot:run

或者,如果使用Gradle:

gradle bootRun

这将启动应用,并监听8080端口。

服务发现与配置管理

集成 Eureka

为了在服务间进行路由请求、实现服务发现和配置管理,我们可以使用 Eureka。添加依赖:

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

配置Eureka客户端:

spring:
  application:
    name: my-service
  cloud:
    discovery:
      enabled: true
      instance:
        hostname: localhost
        ip-address: 127.0.0.1
      registry:
        host: localhost
        port: 8761

使用 Spring Cloud Gateway

为了构建统一的入口并实现路由和过滤功能,我们可以利用 Spring Cloud Gateway。添加依赖:

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

配置路由规则:

spring:
  cloud:
    gateway:
      routes:
      - id: my-service-route
        uri: lb://my-service
        predicates:
        - Path=/my-service/**
实践与案例

异步消息处理:使用 RabbitMQ

在微服务架构中,异步处理通常通过消息队列实现,以保持服务间的解耦。这里以RabbitMQ为例:

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置消息队列

application.yml中配置RabbitMQ连接:

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

发送与接收消息

import org.springframework.amqp.rabbit.core.RabbitTemplate;

public class MessageProducer {

    private final RabbitTemplate rabbitTemplate;

    public MessageProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendMessage(String message) {
        rabbitTemplate.convertAndSend("queue", message);
    }
}

public class MessageConsumer {

    private final RabbitTemplate rabbitTemplate;

    public MessageConsumer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void receiveMessage(String queueName) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.bind(queueName);
        rabbitTemplate.queueDeclare(queueName, false, false, false, null);
        rabbitTemplate.setRoutingKey(queueName);
    }

    private RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        if (ack) {
            System.out.println("Message successfully delivered.");
        } else {
            System.out.println("Message delivery failed: " + cause.getMessage());
        }
    };

    private RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> {
        System.out.println("Message returned: " + message.getBody().toString());
    };
}

微服务安全:OAuth2 与 Spring Security 集成

Spring Security 提供了强大的安全框架,用于实现OAuth2身份验证。以下是一个简单的示例:

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

配置安全设置

application.yml中配置安全策略:

security:
  oauth2:
    client:
      registration:
        google:
          clientId: your-client-id
          clientSecret: your-client-secret
      provider:
        google:
          authorizationUri: https://accounts.google.com/o/oauth2/auth
          tokenUri: https://oauth2.googleapis.com/token
          userInfoUri: https://www.googleapis.com/oauth2/v3/userinfo
          jwkSetUri: https://www.googleapis.com/oauth2/v3/certs
          clientAuthenticationMethod: form
          scope:
            - email
            - profile

实现登录和权限控制

在Spring Security配置类中实现登录处理和权限控制逻辑:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests().requestMatchers("/api/**").authenticated()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .oauth2Login()
            .userInfoEndpoint().jwt().disable()
            .and()
            .addFilterBefore(oauth2ClientAuthenticationProcessingFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    public Oauth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter() {
        Oauth2ClientAuthenticationProcessingFilter filter = new Oauth2ClientAuthenticationProcessingFilter("/login");
        filter.setAuthenticationSuccessHandler(new Oauth2AuthenticationSuccessHandler());
        return filter;
    }

    private class Oauth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                            Authentication authentication) throws IOException {
            // 处理成功登录后的逻辑
        }
    }
}

通过以上案例,我们可以看到,Spring Cloud微服务架构的构建需要关注服务间的通信、配置管理、安全策略等多个方面。随着项目的复杂度增加,对架构设计、代码管理和团队协作的要求也会随之提高。通过实践和不断优化,可以构建出高效、可维护的微服务系统。

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消