《Spring Security 簡易速速上手小冊》第7章 REST API 與微服務安全(2024 最新版)

在這里插入圖片描述

文章目錄

  • 7.1 保護 REST API
    • 7.1.1 基礎知識詳解
    • 7.1.2 重點案例:使用 JWT 進行身份驗證和授權
      • 案例 Demo
    • 7.1.3 拓展案例 1:API 密鑰認證
      • 案例 Demo
      • 測試API密鑰認證
    • 7.1.4 拓展案例 2:使用 OAuth2 保護 API
      • 案例 Demo
      • 測試 OAuth2 保護的 API
  • 7.2 微服務安全最佳實踐
    • 7.2.1 基礎知識詳解
    • 7.2.2 重點案例:使用 JWT 實現服務間認證
      • 案例 Demo
    • 7.2.3 拓展案例 1:使用 Spring Cloud Security 簡化安全配置
      • 案例 Demo
    • 7.2.4 拓展案例 2:API 網關安全
      • 案例 Demo
  • 7.3 API 網關集成
    • 7.3.1 基礎知識詳解
    • 7.3.2 重點案例:集成 Spring Cloud Gateway
      • 案例 Demo
    • 7.3.3 拓展案例 1:限流策略
      • 案例 Demo
    • 7.3.4 拓展案例 2:使用 JWT 進行身份驗證
      • 案例 Demo

7.1 保護 REST API

在數字化時代,REST API是現代Web應用和微服務架構中數據交互的關鍵組成部分。然而,隨著它們的普及和重要性的增加,保護這些API免受惡意攻擊變得尤為重要。本節將探討保護REST API的基礎知識和實用案例。

7.1.1 基礎知識詳解

在構建和維護REST API時,安全性是一個不容忽視的要素。REST API作為應用程序與外界交互的接口,常常面臨著各種安全威脅,包括但不限于身份盜竊、數據泄露、服務拒絕攻擊等。因此,采取有效的安全措施保護REST API是至關重要的。以下是保護REST API時需掌握的基礎知識。

身份驗證 (Authentication)

  • 定義:確定請求者的身份,確保只有合法用戶可以訪問API。
  • 方法
    • 基本認證:通過HTTP頭傳遞用戶名和密碼的簡單認證方法,需要使用HTTPS來避免憑證泄露。
    • 令牌認證:如JWT,通過簽名的令牌確認用戶身份,支持無狀態認證。
    • OAuth/OAuth2:為第三方應用提供限制的訪問權限,而無需暴露用戶的憑證。

授權 (Authorization)

  • 定義:確定已認證的用戶可以執行的操作或訪問的數據。
  • 實現方式
    • 角色基礎的訪問控制(RBAC):根據用戶的角色來決定其權限。
    • 屬性基礎的訪問控制(ABAC):根據屬性(用戶屬性、資源屬性和環境屬性)來動態決定訪問權限。

傳輸安全 (Transport Security)

  • HTTPS:使用SSL/TLS加密HTTP請求和響應,防止數據在傳輸過程中被截獲或篡改。
  • HSTS(HTTP Strict Transport Security):強制客戶端(如瀏覽器)使用HTTPS與服務器建立連接。

數據保護

  • 數據加密:對敏感數據進行加密處理,保護存儲在服務器上或傳輸過程中的數據。
  • 數據脫敏:在公開的響應中避免直接展示敏感數據,如用戶ID、電子郵件地址等。

輸入驗證

  • 目的:防止惡意輸入導致的安全漏洞,如SQL注入、XSS攻擊。
  • 實踐:對所有輸入數據進行驗證,拒絕不符合預期格式的請求。

錯誤處理

  • 優雅處理:錯誤信息應足夠通用,避免泄露敏感信息或系統細節。
  • 日志記錄:記錄錯誤日志,但避免在日志中記錄敏感信息。

限制與節流 (Rate Limiting and Throttling)

  • 目的:防止API濫用,保護后端服務不受惡意攻擊或過載。
  • 實現:限制來自單一來源的請求頻率,當達到限制時返回適當的HTTP狀態碼。

通過這些基礎知識的詳解,我們可以看到保護REST API涉及到多個方面,包括但不限于身份驗證、授權、傳輸安全、數據保護和輸入驗證等。正確實施這些安全措施,可以有效提高API的安全性,保護用戶數據和服務的穩定性。

7.1.2 重點案例:使用 JWT 進行身份驗證和授權

JSON Web Token(JWT)是一種開放標準(RFC 7519),用于在雙方之間安全地傳輸信息作為 JSON 對象。由于其緊湊和自包含的特性,JWT 非常適合用于 REST API 的身份驗證和授權。以下案例將引導你實現 JWT 在 Spring Boot 應用中的身份驗證和授權。

案例 Demo

步驟 1: 引入 JWT 庫依賴

首先,在 Spring Boot 項目的pom.xml中添加對 JWT 庫的依賴。這里我們使用jjwt庫作為示例:

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>

步驟 2: 創建JWT工具類

創建一個JWT工具類JwtUtil,用于生成和驗證 JWT 令牌:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.function.Function;@Component
public class JwtUtil {private String secret = "yourSecretKey"; // 用于簽名的密鑰public String extractUsername(String token) {return extractClaim(token, Claims::getSubject);}public Date extractExpiration(String token) {return extractClaim(token, Claims::getExpiration);}public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {final Claims claims = extractAllClaims(token);return claimsResolver.apply(claims);}private Claims extractAllClaims(String token) {return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();}private Boolean isTokenExpired(String token) {return extractExpiration(token).before(new Date());}public String generateToken(String username) {return Jwts.builder().setSubject(username).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10小時有效期.signWith(SignatureAlgorithm.HS256, secret).compact();}public Boolean validateToken(String token, String username) {final String tokenUsername = extractUsername(token);return (username.equals(tokenUsername) && !isTokenExpired(token));}
}

步驟 3: 實現 JWT 請求過濾器

創建JwtRequestFilter類,它將在每次請求時檢查 JWT 令牌的有效性:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class JwtRequestFilter extends OncePerRequestFilter {@Autowiredprivate MyUserDetailsService userDetailsService;@Autowiredprivate JwtUtil jwtUtil;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {final String authorizationHeader = request.getHeader("Authorization");String username = null;String jwt = null;if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {jwt = authorizationHeader.substring(7);username = jwtUtil.extractUsername(jwt);}if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));SecurityContextHolder.getContext().setAuthentication(authToken);}}chain.doFilter(request, response);}
}

步驟 4: 配置 Spring Security

最后,在 Spring Security 配置中注冊JwtRequestFilter

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtRequestFilter jwtRequestFilter;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/authenticate").permitAll().anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);}
}

通過這些步驟,你的 Spring Boot 應用現在能夠利用 JWT 進行身份驗證和授權,從而保護 REST API 免受未授權訪問。記得保密你的 JWT 密鑰,并定期更新以維護系統安全。

7.1.3 拓展案例 1:API 密鑰認證

API 密鑰認證是一種簡單但有效的安全措施,用于控制對 REST API 的訪問。它適用于服務到服務的通信,其中一個服務需要驗證另一個服務的請求。以下案例演示了如何在 Spring Boot 應用中實現 API 密鑰認證。

案例 Demo

步驟 1: 定義 API 密鑰存儲

首先,假設我們有一個簡單的方式來存儲和驗證 API 密鑰。在實際應用中,這些密鑰可能會存儲在數據庫或配置文件中。這里我們使用一個簡單的 Map 模擬。

import org.springframework.stereotype.Component;import java.util.HashMap;
import java.util.Map;@Component
public class ApiKeyStore {private final Map<String, String> apiKeys = new HashMap<>();public ApiKeyStore() {// 初始化一些API密鑰,實際應用中應該從安全的地方加載apiKeys.put("service1", "key-123");apiKeys.put("service2", "key-456");}public boolean validateKey(String serviceId, String apiKey) {return apiKey.equals(apiKeys.get(serviceId));}
}

步驟 2: 實現 API 密鑰認證過濾器

創建ApiKeyAuthenticationFilter類,該過濾器負責攔截請求并驗證 API 密鑰。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class ApiKeyAuthenticationFilter extends OncePerRequestFilter {@Autowiredprivate ApiKeyStore apiKeyStore;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {String serviceId = request.getHeader("Service-Id");String apiKey = request.getHeader("API-Key");if (serviceId == null || apiKey == null || !apiKeyStore.validateKey(serviceId, apiKey)) {response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid API Key");return;}chain.doFilter(request, response);}
}

步驟 3: 在Spring Security 配置中注冊 API 密鑰認證過濾器

接下來,需要在 Spring Security 配置中添加ApiKeyAuthenticationFilter

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic ApiKeyAuthenticationFilter apiKeyAuthenticationFilter() {return new ApiKeyAuthenticationFilter();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.addFilterBefore(apiKeyAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).authorizeRequests().anyRequest().authenticated().and().csrf().disable();}
}

通過以上步驟,Spring Boot 應用現在能夠使用 API 密鑰進行簡單的身份驗證。任何未提供有效 API 密鑰的請求都將被拒絕訪問。

測試API密鑰認證

啟動應用并嘗試發送請求到受保護的端點,確保在請求頭中包含有效的Service-IdAPI-Key。如果密鑰驗證失敗,應收到 HTTP 401 Unauthorized 錯誤。

這種 API 密鑰認證方法雖然簡單,但在某些場景下非常有效,尤其是在服務對服務的通信中。記得保護好你的 API 密鑰,避免泄露。

7.1.4 拓展案例 2:使用 OAuth2 保護 API

OAuth2是一個開放標準,允許用戶授權第三方應用訪問其服務器資源,而無需將用戶名和密碼直接暴露給第三方應用。這種機制特別適合需要跨應用授權的場景。在本案例中,我們將展示如何在Spring Boot應用中使用OAuth2保護REST API。

案例 Demo

步驟 1: 引入Spring Security OAuth2依賴

首先,確保你的Spring Boot項目中包含了Spring Security OAuth2的依賴。在pom.xml文件中添加:

<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2</artifactId><version>2.3.6.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-jwt</artifactId><version>1.0.10.RELEASE</version>
</dependency>

步驟 2: 配置授權服務器

創建一個配置類AuthorizationServerConfig來配置OAuth2授權服務器。這里我們使用內存中的客戶端和用戶存儲作為示例。

import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("client-id").secret("{noop}client-secret").authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("read", "write").autoApprove(true);}
}

步驟 3: 配置資源服務器

創建一個配置類ResourceServerConfig來配置OAuth2資源服務器。這里我們定義了一些安全限制,以保護API端點。

import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/api/**").authenticated().anyRequest().permitAll();}
}

步驟 4: 定義用戶詳情服務

為了支持"password"授權類型,你需要定義一個UserDetailsService。在這個例子中,我們簡單地在內存中創建一個用戶。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;@Configuration
public class UserDetailsConfig {@Beanpublic UserDetailsService userDetailsService() {InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();manager.createUser(User.withUsername("user").password("{noop}password").roles("USER").build());return manager;}
}

測試 OAuth2 保護的 API

啟動應用后,首先獲取訪問令牌:

  • 對于"password"授權類型,可以使用HTTP請求直接向授權服務器發送用戶名和密碼來獲取令牌。
  • 對于"authorization_code"類型,需要通過用戶代理(如Web瀏覽器)重定向到授權服務器的登錄頁面,用戶登錄后,授權服務器會將令牌重定向回客戶端指定的重定向URI。

一旦獲取到訪問令牌,就可以在請求的Authorization頭中使用它來訪問受保護的資源。

通過以上步驟,你的Spring Boot應用現在能夠利用OAuth2進行身份驗證和授權,從而保護REST API免受未經授權的訪問。這種方法為應用提供了強大的安全性和靈活性,使其能夠安全地與外部應用或服務進行交互。

通過實現這些策略和案例,你可以有效地保護你的 REST API 免受常見安全威脅,確保數據的安全和服務的可用性。記住,安全是一個持續的過程,需要定期審查和更新你的安全策略和實踐。

7.2 微服務安全最佳實踐

微服務架構通過將應用拆分為一系列較小、獨立的服務來提高靈活性和可維護性。然而,這種分散的架構也帶來了新的安全挑戰。保護微服務不僅要求保證數據的安全,還要確保服務間通信的安全。以下是微服務安全的一些基礎知識和最佳實踐。

7.2.1 基礎知識詳解

在微服務架構中,應用被拆分成多個服務,每個服務執行特定的功能,并通過網絡進行通信。這種架構提高了應用的可伸縮性和靈活性,但同時也引入了新的安全挑戰。下面詳細探討微服務安全的關鍵方面和最佳實踐。

服務間通信安全

  • TLS/SSL加密:所有服務間的通信都應通過TLS(傳輸層安全協議)進行加密,確保數據傳輸過程中的機密性和完整性。
  • 雙向SSL:在某些情況下,服務之間還需要相互驗證對方的身份,這可以通過雙向SSL(又稱為客戶端證書認證)來實現。

身份驗證和授權

  • 統一身份認證機制:微服務架構應該有一個集中的身份認證服務,所有服務都應通過這個服務來認證用戶身份。
  • 細粒度授權:授權決策應基于用戶的角色或權限,以及服務的安全策略。可以實現角色基礎訪問控制(RBAC)或更靈活的屬性基訪問控制(ABAC)。

API 網關

  • 集中安全控制:API網關作為微服務架構中的統一入口,可以在這里集中實施身份驗證、授權、流量限制等安全策略。
  • 流量管理:API網關可以對流量進行監控和控制,實現請求限流和熔斷,防止服務被過度使用或惡意攻擊。

安全令牌服務

  • OAuth2和JWT:OAuth2是一個授權框架,允許第三方應用代表用戶訪問其資源,而JWT(JSON Web Token)通常用于在OAuth2流程中攜帶身份驗證和授權信息。

微服務防御措施

  • 輸入驗證:所有服務都應實施嚴格的輸入驗證,以防止SQL注入、跨站腳本(XSS)等攻擊。
  • 依賴管理:定期更新服務的依賴庫,修補已知的安全漏洞。
  • 錯誤處理:適當的錯誤處理可以防止敏感信息泄露,應避免在響應中返回過多的錯誤細節。

安全編碼實踐

  • 代碼審計和掃描:定期進行代碼審計和使用自動化工具掃描代碼,以發現潛在的安全問題。
  • 敏感數據保護:對敏感數據進行加密處理,并在存儲和傳輸時采取適當的保護措施。

通過理解和實施這些基礎知識和最佳實踐,你可以為微服務架構構建堅實的安全基礎,保護你的應用免受各種網絡安全威脅。安全是一個持續的過程,需要不斷地審視、更新和改進安全策略和措施。

7.2.2 重點案例:使用 JWT 實現服務間認證

在微服務架構中,服務間認證是確保每個服務的請求都來自受信任來源的重要機制。使用JSON Web Tokens(JWT)進行服務間認證不僅能提供安全保障,還能確保認證過程的輕量和高效。以下案例演示了如何在Spring Boot微服務架構中實現JWT進行服務間認證。

案例 Demo

步驟 1: 創建JWT工具類

首先,創建一個JwtTokenUtil類來處理JWT的生成和驗證。這個類將提供生成JWT的方法和驗證JWT的方法。

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.function.Function;@Component
public class JwtTokenUtil {@Value("${jwt.secret}")private String secret;@Value("${jwt.expiration}")private Long expiration;public String generateToken(String subject) {return Jwts.builder().setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + expiration)).signWith(SignatureAlgorithm.HS512, secret).compact();}public Boolean validateToken(String token, String subject) {final String tokenSubject = getClaimFromToken(token, Claims::getSubject);return (subject.equals(tokenSubject) && !isTokenExpired(token));}public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {final Claims claims = getAllClaimsFromToken(token);return claimsResolver.apply(claims);}private Claims getAllClaimsFromToken(String token) {return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();}private Boolean isTokenExpired(String token) {final Date expiration = getClaimFromToken(token, Claims::getExpiration);return expiration.before(new Date());}
}

application.properties中配置JWT密鑰和過期時間:

jwt.secret=YourSecretKey
jwt.expiration=604800000  # JWT token的過期時間(這里設置為7天)

步驟 2: 實現服務間請求攔截器

創建一個FeignClientInterceptor攔截器,用于在發送服務間請求時附加JWT。

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class FeignClientInterceptor implements RequestInterceptor {@Autowiredprivate JwtTokenUtil jwtTokenUtil;@Overridepublic void apply(RequestTemplate template) {template.header("Authorization", "Bearer " + jwtTokenUtil.generateToken("service-account"));}
}

步驟 3: 配置服務接收方驗證JWT

在服務接收方,創建一個JwtRequestFilter過濾器來驗證每個進入的請求的JWT。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class JwtRequestFilter extends OncePerRequestFilter {@Autowiredprivate JwtTokenUtil jwtTokenUtil;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {final String requestTokenHeader = request.getHeader("Authorization");String jwtToken = null;if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {jwtToken = requestTokenHeader.substring(7);try {if (!jwtTokenUtil.validateToken(jwtToken, "service-account")) {throw new ServletException("JWT Token is invalid");}} catch (Exception e) {throw new ServletException("JWT Token validation failed", e);}} else {logger.warn("JWT Token does not begin with Bearer String");}chain.doFilter(request, response);}
}

步驟 4: 在服務接收方配置Spring Security使用JWT過濾器

最后,在服務接收方的Spring Security配置中,注冊JwtRequestFilter來驗證進入的請求。

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic JwtRequestFilter jwtRequestFilter() {return new JwtRequestFilter();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class).authorizeRequests().anyRequest().authenticated();}
}

通過上述步驟,微服務架構中的服務間通信將通過JWT進行安全認證,確保只有驗證通過的服務請求才能被接受和處理。這種方法為服務間通信提供了一個安全的認證機制,有助于防止未授權訪問。

7.2.3 拓展案例 1:使用 Spring Cloud Security 簡化安全配置

Spring Cloud Security 提供了一套簡化微服務安全配置的工具,使得實現復雜的安全需求變得更加直接和簡單。利用 Spring Cloud Security,可以輕松實現服務間的安全通信、統一的身份驗證和授權等功能。以下案例將展示如何使用 Spring Cloud Security 在微服務架構中簡化安全配置。

案例 Demo

假設我們有一個微服務架構,需要在服務間實現基于 OAuth2 的安全通信。以下是步驟和示例代碼:

步驟 1: 引入 Spring Cloud Security 依賴

首先,在微服務項目的pom.xml文件中添加 Spring Cloud Security 依賴:

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

步驟 2: 配置資源服務器

在微服務中配置資源服務器,以使用 OAuth2 令牌進行安全驗證。創建一個配置類ResourceServerConfig 繼承 ResourceServerConfigurerAdapter,并使用 @EnableResourceServer 注解來啟用資源服務器。

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll()  // 公開訪問的端點.anyRequest().authenticated();  // 其他所有請求都需要驗證}
}

步驟 3: 配置OAuth2客戶端

如果服務需要作為客戶端訪問其他受保護的服務,可以在application.ymlapplication.properties中配置OAuth2客戶端詳細信息:

security:oauth2:client:clientId: myClientIdclientSecret: myClientSecretaccessTokenUri: http://AUTH-SERVER/oauth/tokenuserAuthorizationUri: http://AUTH-SERVER/oauth/authorizeresource:userInfoUri: http://AUTH-SERVER/userinfo

步驟 4: 使用 Feign 客戶端進行服務間調用

當使用 Feign 客戶端進行服務間調用時,可以通過配置自動攜帶 OAuth2 令牌。首先,確保 Feign 客戶端在請求時攜帶 OAuth2 令牌:

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;public class FeignClientConfig {@Beanpublic RequestInterceptor oauth2FeignRequestInterceptor(OAuth2RestTemplate oAuth2RestTemplate) {return requestTemplate -> {requestTemplate.header("Authorization", "Bearer " + oAuth2RestTemplate.getAccessToken().getValue());};}
}

在 Feign 客戶端接口上應用配置:

@FeignClient(name = "other-service", configuration = FeignClientConfig.class)
public interface OtherServiceClient {// 定義訪問其他服務的方法
}

通過上述步驟,你可以利用 Spring Cloud Security 簡化微服務架構中的安全配置,無需編寫大量的安全配置代碼,就可以實現服務間的安全通信和訪問控制。這種方法不僅減輕了開發負擔,還提高了安全性和可維護性。

7.2.4 拓展案例 2:API 網關安全

在微服務架構中,API網關扮演著重要的角色,它不僅是微服務的統一入口,也是實施安全策略的理想位置。通過在API網關層面集中處理身份驗證、授權、以及流量控制,可以大大簡化單個微服務的安全配置。以下案例將演示如何利用Spring Cloud Gateway實現API網關的安全配置。

案例 Demo

步驟 1: 引入Spring Cloud Gateway依賴

首先,確保在微服務項目的pom.xml中引入Spring Cloud Gateway依賴:

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

步驟 2: 配置API網關路由

接下來,在application.yml中配置API網關的路由規則,將不同的請求轉發到對應的微服務:

spring:cloud:gateway:routes:- id: user-serviceuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- RemoveRequestHeader=Cookie- id: order-serviceuri: lb://ORDER-SERVICEpredicates:- Path=/order/**

這里使用了lb://前綴指定服務發現中的服務ID,RemoveRequestHeader過濾器用來移除敏感的請求頭信息。

步驟 3: 實現全局過濾器進行身份驗證

在API網關中實現一個全局過濾器,用于檢查請求是否包含有效的身份驗證信息,如JWT令牌。創建GlobalAuthFilter類實現GlobalFilter接口:

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {// 檢查請求中的身份驗證信息,例如JWT令牌String token = exchange.getRequest().getHeaders().getFirst("Authorization");if (token == null || !token.startsWith("Bearer ")) {exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);return exchange.getResponse().setComplete();}// 進行令牌驗證...return chain.filter(exchange);}@Overridepublic int getOrder() {return -100; // 設置過濾器優先級}
}

步驟 4: 限流和熔斷配置

使用Spring Cloud Gateway的內置支持來配置限流和熔斷,保護后端微服務不受惡意訪問或流量洪峰的影響。在application.yml中添加相應配置:

spring:cloud:gateway:routes:- id: user-serviceuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- name: RequestRateLimiterargs:key-resolver: "#{@userKeyResolver}"redis-rate-limiter.replenishRate: 10redis-rate-limiter.burstCapacity: 20

這里配置了一個基于Redis的請求速率限制器,key-resolver用于確定限流的鍵,這里假設已經有一個userKeyResolver的Bean定義了用戶識別邏輯。

通過這些步驟,你的API網關將能夠有效地管理和保護微服務架構中的流量,實現統一的身份驗證、授權以及流量控制。通過在API網關集中處理安全邏輯,可以減輕各個微服務的安全負擔,簡化安全配置和管理。

通過實施這些微服務安全最佳實踐,你可以構建一個既靈活又安全的微服務架構,有效保護服務和數據免受各種網絡安全威脅的侵害。記得,安全是一個持續的過程,需要定期審查和更新你的安全策略和實踐。

7.3 API 網關集成

在微服務架構中,API網關作為客戶端和服務之間的中介,承擔著路由請求、聚合響應、身份驗證與授權、以及流量監控等關鍵職責。通過集成API網關,可以在微服務架構中實現統一的入口點,簡化客戶端的交互,同時加強服務的安全性和可管理性。

7.3.1 基礎知識詳解

在現代微服務架構中,API網關不僅僅是一個簡單的路由器,而是服務和數據流的關鍵管理點。它承擔著請求轉發、服務聚合、安全驗證、流量控制和監控等多項職責。深入理解API網關的作用和配置方法對于構建一個高效、安全的微服務系統至關重要。

請求路由

  • 定義:API網關接收外部請求,并根據預定義的規則將請求轉發到對應的后端服務。
  • 作用:實現了請求的負載均衡,提高了系統的可用性和擴展性。

服務聚合

  • 定義:API網關可以將來自多個微服務的數據聚合成一個統一的響應返回給客戶端。
  • 優勢:減少了客戶端需要發送的請求數量,優化了數據交互流程,提高了用戶體驗。

身份驗證與授權

  • 中心化安全策略:在API網關層面集中處理所有進入微服務系統的請求的身份驗證和授權。
  • 優點:簡化了單個微服務的安全配置,提高了安全性和維護性。

流量控制

  • 限流:限制對API的請求速率,防止服務因過載而崩潰。
  • 熔斷:在下游服務不可用時,自動停止向其發送請求,防止故障蔓延。

日志和監控

  • 集中式日志管理:API網關可以記錄所有經過的請求和響應,為系統監控和故障排查提供詳細數據。
  • 監控指標:收集關于請求延遲、成功率和服務健康狀況等關鍵指標,幫助維護系統穩定性。

安全性

  • 傳輸加密:使用HTTPS等技術加密客戶端和API網關之間的通信,保護數據安全。
  • 跨域資源共享(CORS):API網關可以統一處理CORS預檢請求,簡化后端服務的CORS配置。

通過這些基礎知識的了解,我們可以看到API網關在微服務架構中發揮著至關重要的作用,不僅優化了服務的調用和數據的聚合,還大大增強了系統的安全性和可觀測性。正確配置和使用API網關,對于保障微服務架構的健康運行至關重要。

7.3.2 重點案例:集成 Spring Cloud Gateway

Spring Cloud Gateway提供了一個簡單而強大的方式來構建API網關,它與Spring生態系統無縫集成,支持動態路由、過濾和安全性配置。下面的案例將指導你如何在Spring Boot應用中集成Spring Cloud Gateway,實現API網關的基本功能。

案例 Demo

步驟 1: 創建Spring Boot項目并引入依賴

首先,確保你的pom.xml文件中包含了Spring Cloud Gateway的依賴:

<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><version>YOUR_SPRING_CLOUD_VERSION</version></dependency>
</dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>YOUR_SPRING_CLOUD_VERSION</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>

請替換YOUR_SPRING_CLOUD_VERSION為當前Spring Cloud的版本,比如Hoxton.SR9

步驟 2: 配置路由規則

application.yml文件中配置路由規則,將不同的請求路徑路由到對應的微服務:

spring:cloud:gateway:routes:- id: user-serviceuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- StripPrefix=1- id: product-serviceuri: lb://PRODUCT-SERVICEpredicates:- Path=/product/**filters:- StripPrefix=1

這里使用lb://表示使用Spring Cloud的負載均衡,StripPrefix=1過濾器用于移除請求路徑中的第一部分。

步驟 3: 添加全局過濾器進行請求日志記錄

創建一個全局過濾器GlobalLoggingFilter來記錄每個請求的詳細信息:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;@Component
public class GlobalLoggingFilter implements GlobalFilter, Ordered {private final Logger logger = LoggerFactory.getLogger(GlobalLoggingFilter.class);@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {logger.info("Original request path: {}", exchange.getRequest().getPath());return chain.filter(exchange).then(Mono.fromRunnable(() ->logger.info("Response status code: {}", exchange.getResponse().getStatusCode())));}@Overridepublic int getOrder() {return -1; // 設置過濾器順序}
}

步驟 4: 配置安全性和跨域(可選)

如果需要,在API網關層面配置安全性和CORS支持:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;@Configuration
public class GatewayConfig {@Beanpublic CorsWebFilter corsWebFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}

通過這些步驟,你已經成功地在Spring Boot項目中集成了Spring Cloud Gateway,配置了路由規則,添加了全局日志記錄過濾器,并可選地配置了安全性和CORS支持。Spring Cloud Gateway作為API網關,不僅提高了微服務架構的靈活性和可維護性,也加強了整個系統的安全性。

7.3.3 拓展案例 1:限流策略

在面對高流量的情況下,限流是保護微服務不被過度使用、避免系統崩潰的關鍵策略。Spring Cloud Gateway提供了內置的限流功能,可以通過配置輕松實現。以下案例將展示如何在Spring Cloud Gateway中配置限流策略。

案例 Demo

步驟 1: 引入Redis依賴

首先,確保你的項目中包含了Redis的依賴,因為Spring Cloud Gateway的限流特性默認是基于Redis實現的。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

步驟 2: 配置限流規則

application.yml文件中,配置限流規則。你可以根據需要定義不同的限流條件,如IP地址、用戶ID等。以下示例展示了如何基于請求路徑和IP地址進行限流:

spring:cloud:gateway:routes:- id: user-serviceuri: lb://USER-SERVICEpredicates:- Path=/user/**filters:- name: RequestRateLimiterargs:key-resolver: "#{@ipKeyResolver}"redis-rate-limiter.replenishRate: 5redis-rate-limiter.burstCapacity: 10

這里的replenishRate表示每秒允許的請求數,burstCapacity表示在短時間內允許的最大請求數。

步驟 3: 實現KeyResolver

創建一個Bean來定義如何解析限流的key。在這個例子中,我們根據客戶端IP地址進行限流:

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;@Configuration
public class RateLimiterConfig {@BeanKeyResolver ipKeyResolver() {return new KeyResolver() {@Overridepublic Mono<String> resolve(ServerWebExchange exchange) {return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());}};}
}

步驟 4: 測試限流策略

啟動項目,并向配置了限流規則的服務發送請求。如果請求速率超過了配置的replenishRateburstCapacity,則會收到HTTP 429 Too Many Requests錯誤響應。

通過這些步驟,你可以在Spring Cloud Gateway中配置靈活的限流策略,有效防止服務被過度請求,保護系統穩定運行。這種基于Redis的限流機制不僅實現簡單,而且支持高并發處理,非常適合微服務架構中的流量管理需求。

7.3.4 拓展案例 2:使用 JWT 進行身份驗證

在微服務架構中,通過JWT(JSON Web Tokens)進行身份驗證可以有效地管理和驗證用戶和服務的身份。JWT為服務間的安全通信提供了一種簡便的方式。在這個案例中,我們將展示如何在Spring Cloud Gateway中集成JWT進行身份驗證。

案例 Demo

步驟 1: 引入 JWT 依賴

首先,確保你的Spring Boot項目中包含JWT處理庫的依賴。這里我們使用jjwt庫作為示例:

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>

步驟 2: 實現JWT驗證過濾器

在API網關中創建一個自定義的全局過濾器,用于解析和驗證每個請求中的JWT令牌。如果令牌無效,則拒絕訪問。

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;@Component
public class JwtAuthenticationFilter implements GlobalFilter, Ordered {@Value("${jwt.secret}")private String secretKey;@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {String token = exchange.getRequest().getHeaders().getFirst("Authorization");if (token == null || !token.startsWith("Bearer ")) {exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);return exchange.getResponse().setComplete();}try {token = token.substring(7); // Remove Bearer prefixClaims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();// Optionally, further verification logic here} catch (SignatureException e) {exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);return exchange.getResponse().setComplete();}return chain.filter(exchange);}@Overridepublic int getOrder() {return -100;}
}

步驟 3: 配置應用密鑰

application.propertiesapplication.yml中配置JWT的密鑰:

jwt.secret=YourSecretKeyHere

請確保這個密鑰與生成JWT時使用的密鑰相匹配。

步驟 4: 測試JWT身份驗證

現在,當你通過API網關訪問微服務時,需要在HTTP請求的Header中附加有效的JWT令牌。可以使用Postman或其他HTTP客戶端工具來測試這一功能。如果沒有提供令牌或令牌無效,網關將拒絕訪問并返回HTTP狀態碼401 Unauthorized

通過上述步驟,Spring Cloud Gateway現在能夠利用JWT令牌進行身份驗證,從而為微服務架構中的安全通信提供了一層額外的保護。這種方法不僅保障了API的安全性,還提高了系統的可擴展性和維護性。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/716431.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/716431.shtml
英文地址,請注明出處:http://en.pswp.cn/news/716431.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

讀書筆記-三國演義-夏侯惇

夏侯惇&#xff08;公元夏侯惇&#xff08;公元190年-公元220年&#xff09;&#xff0c;字元讓&#xff0c;沛國譙縣&#xff08;今安徽亳州市&#xff09;人&#xff0c;是中國東漢末年至三國時期魏國重要將領之一。他是曹操麾下的得力將領&#xff0c;以勇猛忠誠而聞名于世。…

linux安裝matlab獲取許可證

1.點擊許可證 2. 3. 4. 4.主機ID 打開linux輸入 /sbin/ifconfigether后邊的就是 6.計算機登錄名 打開linux輸入 whoami7. 8. 9.

局域網https自簽名教程

們的客戶是在內網環境里面&#xff0c;所以就只能用自簽名證書來搞&#xff0c;我一想這還不容易&#xff0c;就迅速的百度了一下隨便找了個文章開始照貓畫虎&#xff0c;很快就弄完了&#xff0c;但是弄完后發現還是有問題&#xff0c;而且https 還是報不安全&#xff0c; 1、…

(規劃)24屆春招和25屆暑假實習路線準備規劃

春招&&暑假實習&#xff1a; 1.八股&#xff1a; 可以去一些八股網站上面進行閱讀。 2.項目&#xff1a;至少準備1-2個項目&#xff0c;可以條理清晰的進行項目介紹和難點剖析。 3.算法&#xff1a; hot100 &#xff0c;劍指offer 能刷的很熟&#xff0c;算法關就差…

【R包報錯】使用sceasy包轉換rds文件與h5ad文件報錯PyType_GetFlags

想要將scanpy的h5ad文件轉為rds文件&#xff0c;有一個很方便的包sceasy可以使用&#xff0c;安裝簡單&#xff0c;代碼簡易。 安裝方式 # bioconda package:conda install -c bioconda r-sceasy# R package:devtools::install_github("cellgeni/sceasy")#額外需要…

android系統開發之--ROM編譯,repo使用指南

1、檢出代碼&#xff0c;指定git指定的分支和manifest repo init -u git://xxx/xxx/manifest.git -b <BRANCH> -m <MANIFEST> 這里-m和-b的含義是&#xff1a; 1. 注意到manifest.git本身也是一個git project 2. 所以&#xff0c;-b指定的是使用#1中這個git proj…

我的相關獎項

博士錄取證明 名單第53&#xff1a;https://yzb.bupt.edu.cn/content/content.php?p2_2_651 論文鏈接 第一篇&#xff1a;https://doi.org/10.1186/s13677-022-00373-8 第二篇&#xff1a;https://doi.org/10.1016/j.ipm.2022.103167 第三篇&#xff1a;https://doi.org/10…

Unity 腳本-生命周期常用函數

在Unity中&#xff0c;萬物皆是由組件構成的。 右鍵創建C&#xff03;腳本&#xff0c;拖動腳本到某物體的組件列表。 生命周期相關函數 using System.Collections; using System.Collections.Generic; using UnityEngine;// 必須要繼承 MonoBehaviour 才是一個組件 // 類名…

matplotlib——散點圖和條形圖(python)

散點圖 需求 我們獲得北京2016年三月和十月每天白天最高氣溫&#xff0c;我們現在需要找出氣溫隨時間變化的某種規律。 代碼 # 導入庫 from matplotlib import pyplot as plt import random# 解決中文亂碼 import matplotlib matplotlib.rc("font",family"F…

【筆記】-編程語言以及應用領域

C/C 永遠不會衰敗的語言&#xff0c;適合偏底層&#xff0c;例如&#xff1a;Windows操作系統80%以上都是由C/C完成的&#xff0c;C/C也集成用于寫應用層C/S架構的軟件 JAVA 是真正的跨平臺的語言 “一次編程&#xff0c;到處使用”Java適合應用層的開發&#xff0c;無論是…

Python的錯誤和異常

文章目錄 python的語法錯誤異常異常處理用戶自定義異常定義清理行為預定義的清理行為 python的語法錯誤 語法錯誤&#xff08;Syntax Error&#xff09;是指代碼不符合Python語言的語法規則。當解釋器在執行代碼之前對其進行解析時&#xff0c;如果發現代碼中有語法錯誤&#…

領域驅動設計(Domain-Driven Design DDD)——戰略設計1

一、概述 隨著系統的增長&#xff0c;它會越來越復雜&#xff0c;當我們無法通過分析對象來理解系統的時候&#xff0c;就需要掌握一些操縱和理解大模型的技術了。 最負雄心的企業欲實現一個涵蓋所有業務、緊密集成的系統。因大型公司的業務模型巨大且復雜&#xff0c;很難把它…

2403d,d的108版本更改

原文 編譯器更改 1,在object.d中給TypeInfo_Class添加了.nameSig字段 2,總是在調用點求值像__FILE__此類關鍵字 3,現在可按整數數組轉換十六進制串 4,添加支持插值式序列 庫更改 1,isForwardRange,isBidirectionalRange和isRandomAccessRange現在帶可選元素類型 2,std.uni已…

K8s 鏡像緩存管理 kube-fledged 認知

寫在前面 博文內容為K8s 鏡像緩存管理 kube-fledged 認知內容涉及&#xff1a; kube-fledged 簡單介紹部署以及基本使用 理解不足小伙伴幫忙指正 不必太糾結于當下&#xff0c;也不必太憂慮未來&#xff0c;當你經歷過一些事情的時候&#xff0c;眼前的風景已經和從前不一樣了。…

springboot236基于springboot在線課程管理系統的設計與實現

基于SpringBoot在線課程管理系統的設計與實現 摘要 本文首先介紹了在線課程管理系統的現狀及開發背景&#xff0c;然后論述了系統的設計目標、系統需求、總體設計方案以及系統的詳細設計和實現&#xff0c;最后對在線課程管理系統進行了系統檢測并提出了還需要改進的問題。本系…

Spring Data Redis 使用方式

在Java中操作Redis 1. 在Java中操作Redis1.1 Redis的Java客戶端1.2 Spring Data Redis使用方式1.2.1 介紹1.2.1 環境搭建1.2.3 操作常見類型數據 1. 在Java中操作Redis 1.1 Redis的Java客戶端 Redis 的 Java 客戶端很多&#xff0c;常用的幾種&#xff1a; JedisLettuceSpri…

關于Axios接口請求超時處理與重試的方法教程

在前端開發中&#xff0c;使用Axios作為HTTP客戶端庫進行接口請求是非常常見的做法。然而&#xff0c;在實際開發中&#xff0c;我們經常會遇到網絡不穩定或服務器響應緩慢導致接口請求超時的情況。為了提高用戶體驗和程序的穩定性&#xff0c;我們需要實現接口請求超時的處理與…

UnityAPI的學習——Transform類

Transform類繼承自Component類&#xff0c;并實現了IEnumberable接口。Transform是GameObject必須擁有得一個組件&#xff0c;用來管理所在GameObject對象的坐標位置、選擇角度、和大小縮放。 Transform實現了IEnumberable接口&#xff0c;因此可以在程序中使用foreach()方法快…

echarts vue 動畫效果的水球圖、波浪圖教程

1、安裝插件 前提是已經安裝了echarts&#xff08;我的版本是4.2.1&#xff09; npm install echarts-liquidfill --save 我安裝了3.1.0版本的&#xff0c;結果運行時報錯"TypeError: wave.ensureState is not a function" 原因&#xff1a;echarts版本和echarts-l…

miniconda3徹底刪除虛擬環境

退出虛擬環境&#xff1a;確保您不在要刪除的虛擬環境中。如果在&#xff0c;使用命令 conda deactivate 來退出當前激活的虛擬環境。查看虛擬環境列表&#xff1a;運行命令 conda env list 或 conda info -e 來查看所有存在的虛擬環境及其路徑。刪除虛擬環境&#xff1a;使用命…