SpringData Redis緩存:自定義序列化與過期策略

在這里插入圖片描述

文章目錄

    • 引言
    • 一、Spring Cache與Redis集成基礎
    • 二、Redis緩存配置基礎
    • 三、自定義序列化策略
    • 四、實現自定義序列化器
    • 五、多級緩存配置
    • 六、自定義過期策略
    • 七、緩存注解的高級應用
    • 八、實現緩存預熱與更新策略
    • 九、緩存監控與統計
    • 總結

引言

在現代高并發分布式系統中,緩存扮演著至關重要的角色。Spring Data Redis提供了強大的緩存抽象層,使開發者能夠輕松地在應用中集成Redis緩存。本文將深入探討如何自定義Redis緩存的序列化機制和過期策略,幫助開發者解決緩存數據一致性、內存占用和訪問效率等關鍵問題。通過合理配置Spring Cache注解和RedisCache實現,可顯著提升應用性能,減輕數據庫壓力。

一、Spring Cache與Redis集成基礎

Spring Cache是Spring框架提供的緩存抽象,它允許開發者以聲明式方式定義緩存行為,而無需編寫底層緩存邏輯。結合Redis作為緩存提供者,可以構建高性能的分布式緩存系統。Spring Cache支持多種注解,如@Cacheable、@CachePut、@CacheEvict等,分別用于緩存查詢結果、更新緩存和刪除緩存。Redis的高性能和豐富的數據結構使其成為理想的緩存存儲選擇。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication
@EnableCaching  // 啟用Spring緩存支持
public class RedisCacheApplication {public static void main(String[] args) {SpringApplication.run(RedisCacheApplication.class, args);}
}

二、Redis緩存配置基礎

配置Redis緩存需要創建RedisCacheManager和定義基本的緩存屬性。RedisCacheManager負責創建和管理RedisCache實例,而RedisCache則實現了Spring的Cache接口。基本配置包括設置Redis連接工廠、默認過期時間和緩存名稱前綴等。通過RedisCacheConfiguration可以自定義序列化方式、過期策略和鍵前綴等。這些配置對緩存的性能和可用性有直接影響。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;import java.time.Duration;@Configuration
public class RedisCacheConfig {@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {// 創建默認的Redis緩存配置RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()// 設置緩存有效期為1小時.entryTtl(Duration.ofHours(1))// 設置鍵前綴.prefixCacheNameWith("app:cache:");return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).build();}
}

三、自定義序列化策略

默認情況下,Spring Data Redis使用JDK序列化,這種方式存在效率低、占用空間大、可讀性差等問題。自定義序列化策略可以顯著改善這些問題。常用的序列化方式包括JSON、ProtoBuf和Kryo等。其中JSON序列化便于調試但性能一般,ProtoBuf和Kryo則提供更高的性能和更小的存儲空間。選擇合適的序列化方式需要在性能、空間效率和可讀性之間做權衡。

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisSerializerConfig {@Beanpublic RedisCacheConfiguration cacheConfiguration() {// 創建自定義的ObjectMapper,用于JSON序列化ObjectMapper mapper = new ObjectMapper();// 啟用類型信息,確保反序列化時能夠正確恢復對象類型mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL,JsonTypeInfo.As.PROPERTY);// 創建基于Jackson的Redis序列化器GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(mapper);// 配置Redis緩存使用String序列化器處理鍵,JSON序列化器處理值return RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer));}
}

四、實現自定義序列化器

在某些場景下,Spring提供的序列化器可能無法滿足特定需求,此時需要實現自定義序列化器。自定義序列化器需要實現RedisSerializer接口,覆蓋serialize和deserialize方法。通過自定義序列化器,可以實現特定對象的高效序列化,或者為序列化添加額外的安全措施,如加密解密等。實現時需注意處理序列化異常和空值情況。

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;import java.io.ByteArrayOutputStream;public class KryoRedisSerializer<T> implements RedisSerializer<T> {private final Class<T> clazz;private static final ThreadLocal<Kryo> kryoThreadLocal = ThreadLocal.withInitial(() -> {Kryo kryo = new Kryo();// 配置Kryo實例kryo.setRegistrationRequired(false); // 不要求注冊類return kryo;});public KryoRedisSerializer(Class<T> clazz) {this.clazz = clazz;}@Overridepublic byte[] serialize(T t) throws SerializationException {if (t == null) {return new byte[0];}Kryo kryo = kryoThreadLocal.get();try (ByteArrayOutputStream baos = new ByteArrayOutputStream();Output output = new Output(baos)) {kryo.writeObject(output, t);output.flush();return baos.toByteArray();} catch (Exception e) {throw new SerializationException("Error serializing object using Kryo", e);}}@Overridepublic T deserialize(byte[] bytes) throws SerializationException {if (bytes == null || bytes.length == 0) {return null;}Kryo kryo = kryoThreadLocal.get();try (Input input = new Input(bytes)) {return kryo.readObject(input, clazz);} catch (Exception e) {throw new SerializationException("Error deserializing object using Kryo", e);}}
}

五、多級緩存配置

在實際應用中,往往需要為不同類型的數據配置不同的緩存策略。Spring Cache支持定義多個緩存,每個緩存可以有獨立的配置。通過RedisCacheManagerBuilderCustomizer可以為不同的緩存名稱定制配置,如設置不同的過期時間、序列化方式和前綴策略等。多級緩存配置能夠針對業務特點優化緩存性能。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder;
import org.springframework.data.redis.connection.RedisConnectionFactory;import java.time.Duration;
import java.util.HashMap;
import java.util.Map;@Configuration
public class MultiLevelCacheConfig {@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory,RedisCacheConfiguration defaultConfig) {// 創建不同緩存空間的配置映射Map<String, RedisCacheConfiguration> configMap = new HashMap<>();// 用戶緩存:過期時間30分鐘configMap.put("userCache", defaultConfig.entryTtl(Duration.ofMinutes(30)));// 產品緩存:過期時間2小時configMap.put("productCache", defaultConfig.entryTtl(Duration.ofHours(2)));// 熱點數據緩存:過期時間5分鐘configMap.put("hotDataCache", defaultConfig.entryTtl(Duration.ofMinutes(5)));// 創建并配置RedisCacheManagerreturn RedisCacheManager.builder(connectionFactory).cacheDefaults(defaultConfig).withInitialCacheConfigurations(configMap).build();}
}

六、自定義過期策略

緩存過期策略直接影響緩存的有效性和資源消耗。Spring Data Redis支持多種過期設置方式,包括全局統一過期時間、按緩存名稱設置過期時間,以及根據緩存內容動態設置過期時間。合理的過期策略有助于平衡緩存命中率和數據新鮮度。對于不同更新頻率的數據,應設置不同的過期時間以獲得最佳效果。

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Objects;@Configuration
public class CustomExpirationConfig {@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {// 創建自定義的RedisCacheWriterRedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);// 默認緩存配置RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)); // 默認過期時間1小時// 創建支持動態TTL的RedisCacheManagerreturn new DynamicTtlRedisCacheManager(cacheWriter, defaultConfig);}// 自定義緩存鍵生成器,考慮方法名和參數@Beanpublic KeyGenerator customKeyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method, Object... params) {StringBuilder sb = new StringBuilder();sb.append(target.getClass().getSimpleName()).append(":").append(method.getName());for (Object param : params) {if (param != null) {sb.append(":").append(param.toString());}}return sb.toString();}};}// 自定義RedisCacheManager,支持動態TTLstatic class DynamicTtlRedisCacheManager extends RedisCacheManager {public DynamicTtlRedisCacheManager(RedisCacheWriter cacheWriter,RedisCacheConfiguration defaultConfig) {super(cacheWriter, defaultConfig);}@Overrideprotected RedisCache createRedisCache(String name, RedisCacheConfiguration config) {// 根據緩存名稱動態設置TTLif (name.startsWith("userActivity")) {config = config.entryTtl(Duration.ofMinutes(15));} else if (name.startsWith("product")) {config = config.entryTtl(Duration.ofHours(4));} else if (name.startsWith("config")) {config = config.entryTtl(Duration.ofDays(1));}return super.createRedisCache(name, config);}}
}

七、緩存注解的高級應用

Spring Cache提供了豐富的注解用于管理緩存,包括@Cacheable、@CachePut、@CacheEvict和@Caching等。這些注解能夠精細控制緩存行為,如何何時緩存結果、更新緩存和清除緩存。通過condition和unless屬性,可以實現條件緩存,只有滿足特定條件的結果才會被緩存。合理使用這些注解可以提高緩存的命中率和有效性。

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;@Service
public class ProductService {private final ProductRepository repository;public ProductService(ProductRepository repository) {this.repository = repository;}/*** 根據ID查詢產品,結果會被緩存* 條件:產品價格大于100才緩存*/@Cacheable(value = "productCache",key = "#id",condition = "#id > 0",unless = "#result != null && #result.price <= 100")public Product findById(Long id) {// 模擬從數據庫查詢return repository.findById(id).orElse(null);}/*** 更新產品信息并更新緩存*/@CachePut(value = "productCache", key = "#product.id")public Product updateProduct(Product product) {return repository.save(product);}/*** 刪除產品并清除相關緩存* allEntries=true表示清除所有productCache的緩存項*/@CacheEvict(value = "productCache", key = "#id", allEntries = false)public void deleteProduct(Long id) {repository.deleteById(id);}/*** 復合緩存操作:同時清除多個緩存*/@Caching(evict = {@CacheEvict(value = "productCache", key = "#id"),@CacheEvict(value = "categoryProductsCache", key = "#product.categoryId")})public void deleteProductWithRelations(Long id, Product product) {repository.deleteById(id);}
}

八、實現緩存預熱與更新策略

緩存預熱是指在系統啟動時提前加載熱點數據到緩存中,以避免系統啟動初期大量緩存未命中導致的性能問題。緩存更新策略則關注如何保持緩存數據與數據庫數據的一致性。常見的更新策略包括失效更新、定時更新和異步更新等。合理的緩存預熱與更新策略能夠提高系統的響應速度和穩定性。

import org.springframework.boot.CommandLineRunner;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.util.List;
import java.util.concurrent.TimeUnit;@Component
public class CacheWarmer implements CommandLineRunner {private final ProductRepository productRepository;private final CacheManager cacheManager;private final RedisTemplate<String, Object> redisTemplate;public CacheWarmer(ProductRepository productRepository,CacheManager cacheManager,RedisTemplate<String, Object> redisTemplate) {this.productRepository = productRepository;this.cacheManager = cacheManager;this.redisTemplate = redisTemplate;}/*** 系統啟動時執行緩存預熱*/@Overridepublic void run(String... args) {System.out.println("Performing cache warming...");// 加載熱門產品到緩存List<Product> hotProducts = productRepository.findTop100ByOrderByViewsDesc();for (Product product : hotProducts) {String cacheKey = "productCache::" + product.getId();redisTemplate.opsForValue().set(cacheKey, product);// 設置差異化過期時間,避免同時過期long randomTtl = 3600 + (long)(Math.random() * 1800); // 1小時到1.5小時之間的隨機值redisTemplate.expire(cacheKey, randomTtl, TimeUnit.SECONDS);}System.out.println("Cache warming completed, loaded " + hotProducts.size() + " products");}/*** 定時更新熱點數據緩存,每小時執行一次*/@Scheduled(fixedRate = 3600000)public void refreshHotDataCache() {System.out.println("Refreshing hot data cache...");// 獲取最新的熱點數據List<Product> latestHotProducts = productRepository.findTop100ByOrderByViewsDesc();// 更新緩存for (Product product : latestHotProducts) {redisTemplate.opsForValue().set("productCache::" + product.getId(), product);}}
}

九、緩存監控與統計

緩存監控是緩存管理的重要組成部分,通過監控可以了解緩存的使用情況、命中率、內存占用等關鍵指標。Spring Boot Actuator結合Micrometer可以收集緩存統計數據并通過Prometheus等監控系統進行可視化展示。通過監控數據可以及時發現緩存問題并進行優化,如調整緩存大小、過期時間和更新策略等。

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;@Aspect
@Component
public class CacheMonitorAspect {private final MeterRegistry meterRegistry;private final ConcurrentHashMap<String, AtomicLong> cacheHits = new ConcurrentHashMap<>();private final ConcurrentHashMap<String, AtomicLong> cacheMisses = new ConcurrentHashMap<>();public CacheMonitorAspect(MeterRegistry meterRegistry) {this.meterRegistry = meterRegistry;}/*** 監控緩存方法的執行情況*/@Around("@annotation(org.springframework.cache.annotation.Cacheable)")public Object monitorCacheable(ProceedingJoinPoint joinPoint) throws Throwable {String methodName = joinPoint.getSignature().toShortString();Timer.Sample sample = Timer.start(meterRegistry);// 方法執行前標記,用于判斷是否走了緩存boolean methodExecuted = false;try {Object result = joinPoint.proceed();methodExecuted = true;return result;} finally {// 記錄方法執行時間sample.stop(meterRegistry.timer("cache.access.time", "method", methodName));// 更新緩存命中/未命中計數if (methodExecuted) {// 方法被執行,說明緩存未命中cacheMisses.computeIfAbsent(methodName, k -> {AtomicLong counter = new AtomicLong(0);meterRegistry.gauge("cache.miss.count", counter);return counter;}).incrementAndGet();} else {// 方法未執行,說明命中緩存cacheHits.computeIfAbsent(methodName, k -> {AtomicLong counter = new AtomicLong(0);meterRegistry.gauge("cache.hit.count", counter);return counter;}).incrementAndGet();}}}
}

總結

Spring Data Redis緩存通過提供靈活的配置選項,使開發者能夠根據業務需求自定義序列化方式和過期策略。合理的序列化機制可顯著提升緩存效率,減少網絡傳輸和存儲空間消耗。而科學的過期策略則能平衡數據一致性和緩存命中率,避免緩存穿透和雪崩等問題。在實際應用中,緩存策略應結合業務特點進行差異化配置,如對熱點數據設置較短過期時間以保證數據新鮮度,對變更不頻繁的配置數據設置較長過期時間以減少數據庫查詢。通過緩存預熱、更新策略和監控體系的建立,可以構建高性能、高可靠的分布式緩存系統,有效支撐大規模并發訪問的業務需求。

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

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

相關文章

HOVER:人形機器人的多功能神經網絡全身控制器

編輯&#xff1a;陳萍萍的公主一點人工一點智能 HOVER&#xff1a;人形機器人的多功能神經網絡全身控制器HOVER通過策略蒸餾和統一命令空間設計&#xff0c;為人形機器人提供了通用、高效的全身控制框架。https://mp.weixin.qq.com/s/R1cw47I4BOi2UfF_m-KzWg 01 介紹 1.1 摘…

C++ :頂層const與底層const的區別

頂層const與底層const的區別 定義與核心區別 頂層 const (Top-level const)底層 const (Low-level const)?作用對象變量本身是常量&#xff08;不可修改&#xff09;變量指向或引用的對象是常量&#xff08;不可修改&#xff09;?典型場景指針本身不可變、普通變量為常量指…

Chainlit 自定義元素開發指南:使用 JSX 和受限導入實現交互式界面

自定義元素 Custom Element 類允許你渲染一個自定義的 .jsx 代碼片段。.jsx 文件應當放置在 public/elements/ELEMEN_NAME.jsx 目錄下。 屬性 name 字符串 自定義元素的名稱。它應該與你的JSX文件名相匹配(不包括 .jsx擴展名)。 props 字典 傳遞給 JSX 的屬性。 display El…

Opencv之計算機視覺一

一、環境準備 使用opencv庫來實現簡單的計算機視覺。 需要安裝兩個庫&#xff1a;opencv-python和opencv-contrib-python&#xff0c;版本可以自行選擇&#xff0c;注意不同版本的opencv中的某些函數名和用法可能不同 pip install opencv-python3.4.18.65 -i https://pypi.t…

k8s中PAUSE容器與init容器比較 local卷與hostpath卷比較

目錄 一、PAUSE容器與INIT容器比較 1. Pause 容器 作用 特點 示例 2. Init 容器 作用 特點 示例 3. Pause 容器 vs Init 容器 4. 總結 這兩個哪個先啟動呢&#xff1f; 詳細啟動順序 為什么 Pause 容器最先啟動&#xff1f; 示例 總結 二、local卷與hostpath卷…

Vue3 + TS組件封裝指南

在 Vue 3 TypeScript 中封裝組件時&#xff0c;需要注意以下幾點&#xff1a; 1. Props 定義 使用 defineProps 或 PropType 定義組件的 props&#xff0c;并為其添加類型。 示例&#xff1a; import { defineComponent, PropType } from vue;export default defineComponen…

mybatis_plus的樂觀鎖

樂觀鎖&#xff1a;總是假設最好的情況&#xff0c;每次讀取數據時認為數據不會被修改&#xff08;即不加鎖&#xff09;&#xff0c;當進行更新操作時&#xff0c;會判斷這條數據是否被修改&#xff0c;未被修改&#xff0c;則進行更新操作。若被修改&#xff0c;則數據更新失…

Redis系列:深入理解緩存穿透、緩存擊穿、緩存雪崩及其解決方案

在使用Redis作為緩存系統時&#xff0c;我們經常會遇到“緩存穿透”、“緩存擊穿”和“緩存雪崩”等問題&#xff0c;這些問題一旦出現&#xff0c;會嚴重影響應用性能甚至造成服務不可用。因此&#xff0c;理解這些問題的產生原因和解決方案非常重要。 本文將全面講解緩存穿透…

AT指令集-NBIOT

是什么&#xff1f; 窄帶物聯網&#xff08;Narrow Band Internet of Things, NB-IoT&#xff09;成為萬物互聯網絡的一個重要分支支持低功耗設備在廣域網的蜂窩數據連接&#xff0c;也被叫作低功耗廣域網(LPWAN)NB-IoT支持待機時間長、對網絡連接要求較高設備的高效連接NB-Io…

CBNet:一種用于目標檢測的復合骨干網架構之論文閱讀

摘要 現代頂級性能的目標檢測器在很大程度上依賴于骨干網絡&#xff0c;而骨干網絡的進步通過探索更高效的網絡結構帶來了持續的性能提升。本文提出了一種新穎且靈活的骨干框架——CBNet&#xff0c;該框架利用現有的開源預訓練骨干網絡&#xff0c;在預訓練-微調范式下構建高…

c++中字符串string常用的函數

在C中&#xff0c; std::string 類有許多常用函數&#xff0c;以下是一些常見的&#xff1a; 1. length() 或 size() &#xff1a;返回字符串的長度&#xff08;字符個數&#xff09;&#xff0c;二者功能相同。例如&#xff1a; #include <iostream> #include <str…

《保險科技》

自己在保險行業工作很多年&#xff0c;只是接觸了一些數據的內容&#xff0c;對于保險業務的知識了解的很少&#xff0c;想通過這本書補充一下&#xff0c;但是發現這本書就是一些知識的拼接。 先將保險的歷史&#xff0c;后講保險的定義&#xff0c;然后就是吹噓保險行業和互聯…

藍橋杯第13屆真題2

由硬件框圖可以知道我們要配置LED 和按鍵 一.LED 先配置LED的八個引腳為GPIO_OutPut&#xff0c;鎖存器PD2也是&#xff0c;然后都設置為起始高電平&#xff0c;生成代碼時還要去解決引腳沖突問題 二.按鍵 按鍵配置&#xff0c;由原理圖按鍵所對引腳要GPIO_Input 生成代碼&a…

java之IP 工具類

java程序一直需要獲取物理機的ip&#xff0c;寫了一個ip的工具類&#xff0c;感覺日常所需夠了 import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException;/*** IP 工具類*/ public class IpUtil {public static St…

貪心算法作業參考:P1106,P4995,P5019

貪心算法作業參考&#xff1a;P1106&#xff0c;P4995&#xff0c;P5019 P1106 刪數問題 作業批注&#xff1a; 原作業提交&#xff0c;是刪除k個最大的數。 不一定是刪除最大的數。 參考如下&#xff0c;用例&#xff1a; 輸入&#xff1a; 50074897 2輸出&#xff1a; 4…

雙曲空間學習記錄

文章目錄 前期學習內容雙曲空間中的圖卷積神經網絡 前期學習內容 雙曲空間中的圖卷積神經網絡 250318&#xff1a;這個博客的產生原因是我去看了B站上的一個視頻&#xff0c;up說ppt上傳到github上了&#xff0c;但是我去找了一圈也沒有找到&#xff0c;然后想給他留言&#x…

【ES6新特性】默認參數常見用法

ES6新特性之默認參數的多種用法 &#x1f680;默認參數基礎用法 在ES6中&#xff0c;我們可以直接在函數參數列表中為參數設置默認值&#xff1a; // ES5的實現方式 function greet(name) {name name || Guest;console.log(Hello, ${name}!); }// ES6默認參數寫法 function…

LORA的AB矩陣是針對Transformer的多頭還是MLP

LORA的AB矩陣是針對Transformer的多頭還是MLP Transformer中的矩陣是一個整體還是分開的每個小矩陣 在LORA(Low-Rank Adaptation)中,AB矩陣的應用位置和Transformer中的矩陣拆分方式如下: 1. LORA的AB矩陣作用對象 LORA的AB矩陣主要作用于Transformer的多頭注意力模塊和…

【大模型基礎_毛玉仁】2.4 基于 Encoder-Decoder 架構的大語言模型

更多內容&#xff1a;XiaoJ的知識星球 目錄 2.4 基于 Encoder-Decoder 架構的大語言模型2.4.1 Encoder-Decoder 架構2.4.2 T5 語言模型1&#xff09;T5 模型結構2&#xff09;T5 預訓練方式3&#xff09;T5 下游任務 2.4.3 BART 語言模型1&#xff09;BART 模型結構2&#xff0…

browser-use WebUI + DeepSeek 基于AI的UI自動化解決方案

browser-use WebUI 一、browser-use是什么Browser-use采用的技術棧為&#xff1a; 二、browser-use webui 主要功能使用場景 三、使用教程1.python 安裝2、把項目clone下來3、安裝依賴4、配置環境5、啟動6、配置1.配置 Agent2.配置要用的大模型3.關于瀏覽器的一些設置 四、Deep…