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.mzph.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…