布隆过滤器

Redis-布隆过滤器(Bloom Filter)详解 什么是布隆过滤器 布隆过滤器(Bloom Filter)是 1970 年由布隆提出的,是一种非常节省空间的概率数据结构,运行速度快,占用内存小,但是有一定的误判率且无法删除元素。它实际上是一个很长的二进制向量和一系列随机映射函数组成,主要用于判断一个元素是否在一个集合中。 通常我们都会遇到判断一个元素是否在某个集合中的业务场景,这个时候我们可能都是采用 HashMap的Put方法或者其他集合将数据保存起来,然后进行比较确定,但是如果元素很多的情况下,采用这种方式就会非常浪费空间,最终达到瓶颈,检索速度也会越 阅读详情

布隆过滤器

BLOOM FILTER

参考资料:
https://doc.bulkall.top/spring/bloom-filter/

1、概述:

1.1、背景与定义:

  • 1970 年 由布隆提出
  • 本质:二进制向量(0/1数组集合)以及一系列随机映射函数(hash)
  • 作用:检索一个元素是否在一个集合中
  • 特点:不在一定不在,在有也可能不在
  • 优点:
    1. 空间效率和查询时间相对比一般算法要好,存储空间和查询时间为常数
    2. hash函数之间没有关系,方便由硬件并行实现
    3. 不存储元素本身,可适用于保密性需求
    4. 可以表示全集
  • 缺点:
    1. 存在误识别率(随着存入的元素数量增加,误算率随之增加),可以添加白名单,存储可能误判的元素(元素少的话直接用散列表),出现变种
    2. 难删除,一般情况不能从其中删除元素,
      1. 可以将位图的位变成整型数组(计时器),每插入一个元素相应的计数器加1, 这样删除元素时将对应计数器减掉1就可以了。
      2. 然而要保证安全的删除元素并非如此简单。首先我们必须保证删除的元素的确在布隆过滤器里面. 这一点单凭这个过滤器是无法保证的。
      3. 另外计数器回绕也会造成问题。
      4. 布谷鸟过滤器(Cuckoo filter)

1.2、应用:

  • 网页URL的去重
  • 垃圾邮件的判别
  • 集合重复元素的判别
  • 查询加速(比如基于key-value的[存储系统)
  • 数据库防止查询击穿,使用BloomFilter来减少不存在的行或列的磁盘查找。(缓存穿透)

缓存目标:

  1. 降低数据库的访问压力
  2. 提高响应效率和并发量

缓存设置有效期的原因:

  1. 保证数据库与缓存的数据一致性
  2. 降低冷缓存数据占用过多的内存空间

当缓存失效或没有抵挡住流量,流量直接涌入到数据库,在高并发的情况下,可能直接击垮数据库,导致整个系统崩溃。

正常流程:

  1. 接收请求,请求缓存
  2. 缓存中有值,直接返回,否则走3
  3. 查库。有值,刷缓存,返回,否则走4
  4. 直接报错

缓存穿透:缓存和数据库均没有用户所需值,导致每次需要访问数据库,高并发或有人利用不存在的Key频繁攻击时,DB直接宕机(数据误删、知道不存在的key恶意攻击)

  • 缓存默认值或者空(null)

    • 分析业务请求,如果是正常业务请求时发生缓存穿透现象,可针对相应的业务数据,在数据库查询不存在时,将其缓存为空值(null)或默认值。
    • 需要注意的是,针对空值的缓存失效时间不宜过长,一般设置为5分钟之内。当数据库被写入或更新该key的新数据时,缓存必须同时被刷新,避免数据不一致。
  • 业务逻辑前置校验

    • 业务入口合法性校验,检查请求参数是否合理、是否包含非法值、是否恶意请求等,提前有效阻断非法请求
  • 布隆过滤器请求白名单

    • 在写入数据时,使用布隆过滤器进行标记(相当于设置白名单),业务请求发现缓存中无对应数据时,可先通过查询布隆过滤器判断数据是否在白名单内,如果不在白名单内,则直接返回空或失败。
  • 用户黑名单限制

    • 当发生异常情况时,实时监控访问的对象和数据,分析用户行为,针对故意请求、爬虫或攻击者,进行特定用户的限制;
  • 随机而动:针对具体情况,采用对应的措施

缓存雪崩:大量热点key同一时间过期(还有一种可能:缓存服务器挂了),当缓存中大量热点缓存采用了相同的实效时间,就会导致缓存在某一个时刻同时实效,请求全部转发到数据库,从而导致数据库压力骤增,甚至宕机

  • 控制失效时间,尽量不让同一时间同时失效,每个时间后边加随机数,让其均匀失效
  • 缓存单线程写(队列或者锁),并发量低
  • 异步更新缓存,适用不严格要求缓存一致性的场景
  • 双key策略,主key设置过期时间,备key不设置过期时间,当主key失效时,直接返回备key值
  • 构建缓存高可用集群(针对缓存服务故障情况)。
  • 当缓存雪崩发生时,服务熔断、限流、降级等措施保障。

缓存击穿:某一个热点key同一时间过期(缓存雪崩的子集)

  • 互斥锁(muter key),只让一个线程构建缓存,其他线程等待构建缓存执行完毕,重新从缓存中获取数据。单机通过synchronized或lock来处理,分布式环境采用分布式锁。
  • 异步更新缓存,适用不严格要求缓存一致性的场景
  • ”提前“使用互斥锁(Mutex Key):在value内部设置一个比缓存(Redis)过期时间短的过期时间标识,当异步线程发现该值快过期时,马上延长内置的这个时间,并重新从数据库加载数据,设置到缓存中去。

数据库层只要可以横向扩展,解决一切问题

1.3、api集成

  • redission

    @SpringBootTest
    public class RedissonDemoTest {
        @Resource
        RedissonClient redissonClient;
        @Test
        void contextLoads() {
            RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("phoneList");
            //初始化布隆过滤器:预计元素为1000000L,误差率为3%
            bloomFilter.tryInit(1000000L,0.03);
            //将号码10086插入到布隆过滤器中
            bloomFilter.add("10086");
            //判断下面号码是否在布隆过滤器中
            System.out.println(bloomFilter.contains("123456"));//false
            System.out.println(bloomFilter.contains("10086"));//true
        }
    }
    
  • guava

    public class GuavaBloomFilterTest {
        @Test
        public void test() {
            //插入多少数据
            int insertions = 1000000;
            //期望的误判率
            double fpp = 0.02;
            //初始化一个存储string数据的布隆过滤器,默认误判率是0.03
            BloomFilter<String> bf = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), insertions, fpp);
            //用于存放所有实际存在的key,用于是否存在
            Set<String> sets = new HashSet<>(insertions);
            //用于存放所有实际存在的key,用于取出
            List<String> lists = new ArrayList<>(insertions);
            //插入随机字符串
            for (int i = 0; i < insertions; i++) {
                String uuid = UUID.randomUUID().toString();
                bf.put(uuid);
                sets.add(uuid);
                lists.add(uuid);
            }
            int rightNum = 0;
            int wrongNum = 0;
            for (int i = 0; i < 10000; i++) {
                // 0-10000之间,可以被100整除的数有100个(100的倍数)
                String data = i % 100 == 0 ? lists.get(i / 100) : UUID.randomUUID().toString();
                //这里用了 might ,看上去不是很自信,所以如果布隆过滤器判断存在了,我们还要去 sets 中实锤
                if (bf.mightContain(data)) {
                    if (sets.contains(data)) {
                        rightNum++;
                        continue;
                    }
                    wrongNum++;
                }
            }
            BigDecimal percent = new BigDecimal(wrongNum).divide(new BigDecimal(9900), 2, RoundingMode.HALF_UP);
            BigDecimal bingo = new BigDecimal(9900 - wrongNum).divide(new BigDecimal(9900), 2, RoundingMode.HALF_UP);
            System.out.println("在100W个元素中,判断100个实际存在的元素,布隆过滤器认为存在的:" + rightNum);
            System.out.println("在100W个元素中,判断9900个实际不存在的元素,误认为存在的:" + wrongNum + ",命中率:" + bingo + ",误判率:" + percent);
        }
    }
    
  • hutool

  • 自己实现

    /**
     * 自定义布隆过滤器
     * 哈希函数(n个)
     * 二进制向量
     */
    public class CustomBloomFilter {
        /**
         * 长度10亿的比特位
         */
    //    private static final int DEFAULT_SIZE = 256 << 22;
        private static final int DEFAULT_SIZE = 1000000;
        /**
         * 不同哈希函数的种子,一般应取质数
         * 为了降低错误率,使用加法 hash 算法,所以定义一个8个元素的质数数组
         */
        private static final int[] SEEDS = {3,5,7,11,13,31,37,61};
        /**
         * 相当于构建 8 个不同的 hash 算法 HashFunction 越多,误判率越低,也越慢
         */
        public static final HashFunction[] FUNCTIONS = new HashFunction[SEEDS.length];
        /**
         * 初始化布隆过滤器的 BitSet
         * BitSet 即“位图”,是一个很长的 “0/1”序列,他的功能就是存储0或者1
         */
        public static final BitSet BIT_SET = new BitSet(DEFAULT_SIZE);
    
        public static void add(String value){
            if(StringUtils.isNotBlank(value)){
                for (HashFunction f : FUNCTIONS) {
                    //计算value的hash值并修改bitmap中相应的位置为true
                    BIT_SET.set(f.hash(value),true);
                }
            }
        }
        public static boolean contains(String value){
            if(StringUtils.isBlank(value)){
                return false;
            }
            boolean ret =false;
            for (HashFunction f : FUNCTIONS) {
                ret = BIT_SET.get(f.hash(value));
                if(!ret){
                    break;
                }
            }
            return ret;
        }
        public static void main(String[] args) {
            //初始化functions
            for (int i = 0; i < SEEDS.length; i++) {
                FUNCTIONS[i] = new HashFunction(DEFAULT_SIZE,SEEDS[i]);
            }
            long startTime = System.currentTimeMillis();
            //添加数据
            for (int i = 0; i < DEFAULT_SIZE/100; i++) {
                add(String.valueOf(i));
            }
            System.err.println(System.currentTimeMillis()-startTime);
    
            String id = "123456789";
            add(id);
            System.err.println(contains(id));
            System.err.println(contains("100000000"));
    
        }
        static class HashFunction {
            private final int size;//数组长度,hash生成值的最大值
    
            private final int seed;//不同哈希函数的种子,一般应取质数
    
            public HashFunction(int size, int seed) {
                this.seed = seed;
                this.size = size;
            }
            /**
             * 计算hash
             * @param value
             * @return
             */
            public int hash(String value) {
                int result = 0;
                int len = value.length();
                for (int i = 0; i < len; i++) {
                    result = seed * result + value.charAt(i);
                }
                return (size - 1) & result;
            }
        }
    }
    

2、业务使用

2.1、使用流程:

image-20221210150258222

2.2、demo演示:

缓存使用redis

工具使用redission

pom依赖:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>31.1-jre</version>
    </dependency>

    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson</artifactId>
        <version>3.16.1</version>
    </dependency>
    <dependency>
        <groupId>org.redisson</groupId>
        <!-- for Spring Data Redis v.2.2.x -->
        <artifactId>redisson-spring-data-22</artifactId>
        <version>3.16.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
     <!--lombok 依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
</dependencies>
配置文件:
server:
  port: 8045
spring:
  redis:
    #超时时间
    timeout: 1000000ms
    #服务器地址
    host: 127.0.0.1
    #端口
    port: 6379
    #数据库
    database: 0
    #密码
    password: ljc123456
    lettuce:
      pool:
        #最大连接数 默认8
        max-active: 1024
        #最大连接阻塞等待时间,默认-1ms
        max-wait: 1000000ms
        #最大空闲连接
        max-idle: 200
        #最小空闲连接
        min-idle: 20
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/auth?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
    username: root
    password: 950824
    hikari:
      # 连接池名 springboot 自带
      pool-name: DateHikariCP
      # 最小空闲连接数
      minimum-idle: 5
      # 空闲连接存活最大时间,默认600000(10分钟)
      idle-timeout: 180000
      # 最大连接数,默认10
      maximum-pool-size: 10
      # 从连接池返回的连接的自动提交
      auto-commit: true
      # 连接最大存活时间,0表示永久存活,默认1800000(30分钟)
      max-lifetime: 1800000
      # 连接超时时间,默认30000(30秒)
      connection-timeout: 30000
      # 测试连接是否可用的查询语句
      connection-test-query: SELECT 1
主要业务类:
启动类:
/**
 * Spring Boot 整合布隆过滤器 demo
 */
@SpringBootApplication
@EnableScheduling//用来定时重刷布隆过滤器数据
@MapperScan("top.jkxljc.bloom.mapper")
public class SpringBootBloomFilterApplication {

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

}
定时任务重刷:
/**
 * 定时任务 刷 布隆过滤器中的数据
 */
@Component
public class ProductSchedule {
    @Resource
    ProductService productService;
    /**
     * 每天一点执行
     * 目的是为了刷新那些被删除掉的产品
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void refreshBloom() {
        productService.refreshBloom();
    }
}
mapper+实体
/**
 * 产品demo(Product)表实体类
 */
@Data
public class Product implements Serializable {
    /**
     * 主键
     **/
    private Integer id;
    /**
     * 名称
     **/
    private String productName;
    /**
     * 价钱
     **/
    private Double productPrice;
    /**
     * 数量
     **/
    private Integer productNum;
    /**
     * 添加时间
     **/
    private LocalDateTime addTime;
    /**
     * 创建人
     **/
    private String addBy;
    /**
     * 更新时间
     **/
    private LocalDateTime updateTime;
    /**
     * 更新人
     **/
    private String updateBy;
}
/**
 * 产品demo(Product)表数据库访问层
 */
public interface ProductMapper extends BaseMapper<Product> {
}
controller
@RestController
@RequestMapping("/product")
public class ProductController {
    @Resource
    ProductService productService;
    @GetMapping("/{id}")
    public String getProduct(@PathVariable Integer id) {
        Product product = productService.getProductById(id);
        if (BeanUtil.isEmpty(product)) {
            return "暂无该产品!";
        }
        return JSONUtil.toJsonStr(product);
    }

    @PostMapping("/add")
    public Boolean addProduct(@RequestBody Product product) {
        return productService.addProduct(product);
    }

    @DeleteMapping("/{id}")
    public Boolean delProduct(@PathVariable Integer id) {
        return productService.removeById(id);
    }
}
业务类:
/**
 * 产品demo(Product)表服务接口
 */
public interface ProductService extends IService<Product> {
    Product getProductById(Integer id);

    Boolean addProduct(Product product);
    void refreshBloom();
}
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    private static final String BLOOM_STR = "product_list_bloom";

    private static final String REDIS_CACHE = "product_list";
    @Resource
    RedissonClient redissonClient;

    RBloomFilter<Integer> bloomFilter;
    /**
     * 启动时候将产品加入到 布隆过滤器中
     */
    @PostConstruct
    public void init() {
        bloomFilter = redissonClient.getBloomFilter(BLOOM_STR, new JsonJacksonCodec());
        this.refreshBloom();
    }

    @Override
    public void refreshBloom() {
        bloomFilter.delete();
        //初始化布隆过滤器:预计元素为 1000000L (这个值根据实际的数量进行调整),误差率为3%
        bloomFilter.tryInit(1000000L, 0.03);
        List<Integer> productIdList = this.list(new LambdaQueryWrapper<Product>().select(Product::getId))
                .stream().map(Product::getId).collect(Collectors.toList());
        productIdList.forEach(bloomFilter::add);
    }

    @Override
    public Product getProductById(Integer id) {
        // 走布隆过滤器筛选一下,防止被缓存穿透
        boolean contains = bloomFilter.contains(id);
        // 如果布隆过滤器判断当前产品id 存在,则去查询数据库
        if (contains) {
            // 先去缓存中查
            RMap<Integer, String> productCache = redissonClient.getMap(REDIS_CACHE);
            String cacheProduct = productCache.get(id);
            if (StrUtil.isNotEmpty(cacheProduct)) {
                // 如果缓存中不是空 则返回
                return JSONUtil.toBean(cacheProduct, Product.class);
            }
            Product product = this.getById(id);
            // 如果查到了数据,那么存一份到 redis 中去
            if (BeanUtil.isNotEmpty(product)) {
                productCache.put(id, JSONUtil.toJsonStr(product));
                return product;
            }
        } else {
            log.info("布隆过滤器中不存在产品id:{}的数据", id);
        }
        return null;
    }

    @Override
    public Boolean addProduct(Product product) {
        boolean success = this.save(product);
        // 数据添加成功后,往 redis 缓存中 和 布隆过滤器中添加数据
        if (success) {
            final Integer id = product.getId();
            RMap<Integer, String> redisCache = redissonClient.getMap(REDIS_CACHE);
            redisCache.put(id, JSONUtil.toJsonStr(product));
            bloomFilter.add(id);
        }
        return success;
    }
}
  } else {
            log.info("布隆过滤器中不存在产品id:{}的数据", id);
        }
        return null;
    }

    @Override
    public Boolean addProduct(Product product) {
        boolean success = this.save(product);
        // 数据添加成功后,往 redis 缓存中 和 布隆过滤器中添加数据
        if (success) {
            final Integer id = product.getId();
            RMap<Integer, String> redisCache = redissonClient.getMap(REDIS_CACHE);
            redisCache.put(id, JSONUtil.toJsonStr(product));
            bloomFilter.add(id);
        }
        return success;
    }
}
一篇吃透布隆过滤器(Bloom Filter)及其使用场景 布隆过滤器(英语:Bloom Filter)是1970年由布隆提出的。它实际上是一个很长的二进制向量和一系列随机映射函数。布隆过滤器可以用于检索一个元素是否在一个集合中 阅读详情

相关推荐

【Redis】布隆过滤器(Bloom Filter)

布隆过滤器(Bloom Filter)是1970年由布隆提出的。它实际上是一个很长的二进制向量和一系列随机映射函数。布隆过滤器可以用于检索一个元素是否在一个集合中。它的优点是空间效率和查询时间都比一般的算法要好的多,缺点是有一定的误识别率和删除困难。可以把布隆过滤器理解为一个set集合,我们可以通过add往里面添加元素,通过contains来判断是否包含某个元素。

weixin_44823875的博客 2873

布隆过滤器深度实战:详解原理、场景与SpringBoot+Redis高性能实现

【全网最硬核布隆过滤器指南】万字长文从哈希碰撞本质出发,深度剖析布隆过滤器的位数组与多哈希函数核心机制,结合Google Guava与Redisson源码解读,手把手教你通过SpringBoot+Redis构建支持动态扩容的工业级布隆过滤器。本文不仅详解误判率公式推导与参数调优方法论,更包含缓存穿透防护、十亿级数据去重等6大真实场景解决方案,最后通过JMeter压测验证过滤器性能,助你掌握这个让数据库查询性能翻倍的核心技术。随文附赠可动态扩容的布隆过滤器SpringBoot工程源码,技术深度与实战价值兼备!

Zyw907155124的博客 2万+

hbase之布隆过滤器

一、布隆过滤器布隆过滤器(Bloom Filter)是1970由布隆提出的。通过一个很长的二进制向量于一系列随即哈希函数生成。下面我就将通过以下小节来介绍布隆过滤器:1、原因与结构解析2、数学公式1.1 原因与结构解析首先,我们应当知道,hash是内存中使用的经典数据结构。当我们需要判读一个元素是否在一个集合当中时,我们可以用哈希表来判断。在集合较小的情况下,hash是可行而且高效的。然而数据量以...

qq_38180223的博客 9904

布隆过滤器Bloom Filter简介

背景: 如果在平时我们要判断一个元素是否在一个集合中,通常会采用查找比较的方法,下面分析不同的数据结构查找效率: 采用线性表存储,查找时间复杂度为O(N) 采用平衡二叉排序树(AVL、红黑树)存储,查找时间复杂度为O(logN) 采用哈希表存储,考虑到哈希碰撞,整体时间复杂度也要O[log(n/m)] 当需要判断一个元素是否存在于海量数据集合中,不仅查找时间慢,还会占用大量存储空间,接下来看一下布隆过滤器如何解决这个问题 1、什么是布隆过滤器: 布隆过滤器是一种空间效率很高的随机数据结..

张维鹏的博客 3026

布隆过滤器——(C++)

布隆过滤器布隆过滤器的提出布隆过滤器概念哈希函数和布隆过滤器的长度位图的代码实现布隆过滤器Set接口Test接口布隆过滤器的删除布隆过滤器的优点布隆过滤器的缺点哈希分割 布隆过滤器的提出 我们在使用新闻客户端看新闻时,它会给我们不停地推荐新的内容,它每次推荐时要去重,去掉那些已经看过的内容。问题来了,新闻客户端推荐系统如何实现推送去重的? 用服务器记录了用户看过的所有历史记录,当推荐系统推荐新闻时会从每个用户的历史记录里进行筛选,过滤掉那些已经存在的记录。 如何快速查找呢? 用哈希表存储用户记录,缺点:浪

weixin_45599288的博客 4277

哈希的应用 —— 布隆过滤器

布隆过滤器是由布隆(Burton Howard Bloom)在1970年提出的一种紧凑型的、比较巧妙的概率型数据结构,特点是高效地插入和查询。布隆过滤器其实就是位图的一个变形和延申,虽然无法避免存在哈希冲突,但我们可以想办法降低误判的概率。当一个数据映射到位图中时,布隆过滤器会用多个哈希函数将其映射到多个比特位,当判断一个数据是否在位图当中时,需要分别根据这些哈希函数计算出对应的比特位,如果这些比特位都被设置为1则判定为该数据存在,否则则判定为该数据不存在。

2021dragon的博客 2693

布隆过滤器 - Redis 布隆过滤器,Guava 布隆过滤器 BloomFilter

文章目录布隆过滤器 - Redis 布隆过滤器,Guava 布隆过滤器 BloomFilter1、布隆过滤器的起源,用途2、布隆过滤器的概念3、布隆过滤器的优缺点1、优点2、缺点4、应用场景5、布隆过滤器的工作原理6、布隆过滤器的设计 布隆过滤器 - Redis 布隆过滤器,Guava 布隆过滤器 BloomFilter 1、布隆过滤器的起源,用途 布隆过滤器(Bloom Filter)是197...

简简单单Onlinezuozuo 1万+

高通ISP模块全解析:从Raw到JPEG的18个关键处理步骤(附避坑指南)

本文全面解析高通ISP模块从Raw到JPEG的18个关键处理步骤,涵盖原始数据预处理、色彩科学处理链、画质增强与降噪等核心环节。通过实战调优经验,揭示ISP架构中的技术原理与工程实践要点,帮助开发者避免常见问题,提升移动影像处理质量。

weixin_30399155的博客 361

什么是布隆过滤器?如何使用?

布隆过滤器(英语:Bloom Filter)是1970年由布隆提出的。它实际上是一个很长的二进制向量和一系列随机映射函数。布隆过滤器可以用于检索一个元素是否在一个集合中如果想判断一个元素是不是在一个集合里,一般想到的是将集合中所有元素保存起来,然后通过比较确定。链表、树、散列表(又叫哈希表,Hash table)等等数据结构都是这种思路。但是随着集合中元素的增加,我们需要的存储空间越来越大。同时检索速度也越来越慢,上述三种结构的检索时间复杂度分别为O(n),O(log n),O(1)。

致力于不留技术债务cuizb.top 2万+

英飞凌TC3xx SWAP机制深度解析:从内存映射到SOTA实战

本文深度解析英飞凌TC3xx的SWAP机制,从内存映射原理到SOTA实战应用。通过硬件级双Bank切换实现汽车ECU远程升级与自动回滚,详细讲解UCB配置、Flash地址映射及避坑指南,帮助开发者高效实现稳定可靠的固件更新方案。

weixin_42741930的博客 311

Cherry Studio 新手必看:5分钟搞定MCP服务器配置(附常见问题解决)

本文为Cherry Studio新手提供了详细的MCP服务器配置指南。文章从核心概念入手,解释了Cherry Studio作为MCP客户端如何通过MCP协议安全、标准化地扩展AI助手能力。重点讲解了uv和Bun环境的安装与常见网络问题的解决方案,并演示了如何添加首个MCP服务器(如mcp-server-fetch),助你快速构建可扩展的智能工作流。

corn8的博客 596

Redis 之布隆过滤器

1、布隆过滤器使用场景   比如有如下几个需求:   ①、原本有10亿个号码,现在又来了10万个号码,要快速准确判断这10万个号码是否在10亿个号码库中?   解决办法一:将10亿个号码存入数据库中,进行数据库查询,准确性有了,但是速度会比较慢。   解决办法二:将10亿号码放入内存中,比如Redis缓存中,这里我们算一下占用内存大小:10亿*8字节=8GB,通过内存查询,准确性和速度都有了,但是大约8gb的内存空间,挺浪费内存空间的。   ②、接触过爬虫的,应该有这么一个需求,需要爬虫的网站千千

伟大是熬出来的 1万+

Jitsi中的Prosody(谐音:破扫敌)介绍

凭借其灵活的插件系统、强大的安全性和出色的性能,Prosody 成为许多企业和开发者构建定制化通信解决方案的首选。在 Jitsi 的多方视频会议场景中,Prosody 不仅处理基本的信令任务,还需要与其他组件(如 Jitsi Videobridge)协作,确保视频流的正确分发和控制。Prosody 提供了丰富的插件系统,允许开发者通过模块扩展其功能。Prosody 就是一个实现 XMPP 协议的服务器,它支持 XMPP 协议的标准功能,如消息传递、群组聊天、传送状态信息等,并提供了高效、可扩展的服务。

江左散人的专栏 1168

【Redis】布隆过滤器

布隆过滤器的简介、Redis的布隆过滤器的实现

人类所有真实的快乐,一定是恒久的努力 4288

PyTorch实战:3D U-Net医学图像分割从零搭建(附完整代码)

本文详细介绍了如何使用PyTorch从零搭建3D U-Net模型进行医学图像分割,涵盖三维卷积实现、模块化架构设计、医学图像专属优化策略及完整训练流程。通过实战代码演示,帮助开发者掌握UNet-3D在CT、MRI等三维医学图像分割中的应用,提升肝脏肿瘤分割、肺结节检测等任务的准确性。

weixin_29061997的博客 330

2024年Unity 面试题 |五萬字 二佰道| Unity面试题大全,面试题总结【全网最全,收藏一篇足够面试】

正所谓 金三银四 ,又到了找工作的大好时机了,不知道大家有没有意向找一份更好的工作呢~ 之前写了很多Unity的学习和实例文章,但是面试题部分还没有一个系统的整理。 那本篇文章就来整理一下Unity中一些常见的面试题,说不准就会面试的时候就会遇到! 本篇文章会将Unity所有方面的面试资料都融会贯通,绝对是2022年Unity面试领域最实用的文章啦!

努力前行,总会成为自己心中的那道光 17万+

Java实现布隆过滤器

布隆过滤器 海量数据处理以及缓存穿透这两个场景让我认识了 布隆过滤器 ,我查阅了一些资料来了解它,但是很多现成资料并不满足我的需求,所以就决定自己总结一篇关于布隆过滤器的文章。希望通过这篇文章让更多人了解布隆过滤器,并且会实际去使用它! 下面我们将分为几个方面来介绍布隆过滤器: 什么是布隆过滤器? 布隆过滤器的原理介绍。 布隆过滤器使用场景。 通过 Java 编程手动实现布隆过滤器。 利用 Google 开源的 Guava 中自带的布隆过滤器。 Redis 中的布隆过滤器。 什么是布隆过滤器? 首先,我

在下令狐的博客 7408

C#量化交易的市场数据采集与分析:从0到1构建你的‘数据雷达’——对比5大神器,代码实战全解析!

数据是量化交易的‘氧气’,而好的数据采集与分析是你的‘呼吸机’!本文5大神器+代码实战,总有一款适合你!(本文代码均经过测试,但请根据实际需求调整!

java专栏 734

数据结构-布隆过滤器和可逆布隆过滤器

在解决缓存穿透问题时,往往会用到一种高效的数据结构-布隆过滤器,其能够快速过滤掉不存在的非法请求,但其也存在一定的误差,即少量不存在的请求也会被放过去。本文对布隆过滤器家族进行介绍,除了常见的普通布隆过滤器(Bloom Filters),还有计数布隆过滤器(Couting Bloom Filters)和可逆布隆过滤器(Invertible Bloom Filters)。

zhuohuashiyi 1980

结构力学本构模型:复合材料模型:复合材料热力学行为技术教程_2024-08-07_06-54-53.Tex

热塑性复合材料是一种由热塑性树脂基体和增强纤维组成的复合材料。与热固性复合材料不同,热塑性复合材料在加热时可以软化,冷却时硬化,这一过程可以重复进行,因此它们具有可回收和可再加工的特性。热塑性树脂,如聚酰胺(尼龙)、聚碳酸酯、聚醚醚酮(PEEK)等,与碳纤维、玻璃纤维等增强材料结合,可以制备出具有高强度、高刚度和良好耐热性的复合材料。热粘弹性理论是研究材料在温度变化和时间依赖性载荷作用下的变形和应力响应。复合材料,由于其独特的微观结构,展现出复杂的热粘弹性行为。

810

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Google布隆过滤器与Redis布隆过滤器详解

一、什么是布隆过滤器? 布隆过滤器可以用来判断一个元素是否在一个集合中。它的优势是只需要占用很小的内存空间以及有着高效的查询效率。 对于布隆过滤器而言,它的本质是一个位数组:位数组就是数组的每个元素都只占用1bit ,并且每个元素只能是0或者1 布隆过滤器除了一个位数组,还有 K 个哈希函数。当一个元素加入布隆过滤器中的时候,会进行如下操作: 使用K个哈希函数对元素值进行K次计算,得到...

weixin_36091906的博客 962

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

上一篇: 数据库基础知识-01:
ADCQprogrammer
博客等级 码龄7年 4粉丝 21原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值