# 请求缓存器

请求缓存器主要是缓存风铃虫里所有抓取过的资源。

请求缓存器的基本功能如下:

  • 查询此资源是否存在指定的的集合中
  • 将资源存储到指定名字的集合中
  • 清空指定名字的缓存集合
  • 查询指定名字的缓存集合里的资源数量

风铃内置的请求缓存器有:

  • 内存请求缓存器
  • redis请求缓存器

# 内存请求缓存器

        //获取风铃虫实例
        Crawler crawler = ...
        //注意此步骤一定要在风铃启动之前进行
        crawler.setRequestCache(new InMemoryRequestCache())
        //启动风铃虫
        crawler.start();

内存缓存器是基于内存实现,它也是风铃虫默认使用的资源调度器。

# Redis请求缓存器

        //获取风铃虫实例
        Crawler crawler = ...
        //注意此步骤一定要在风铃启动之前进行
        RedisRequestCache redisRequestCache = new RedisRequestCache(redisTemplate);
        crawler.setRequestCache(redisRequestCache)
        //启动风铃虫
        crawler.start();

# 自定义请求缓存器

在某些情况下,可能会需要使用到自定义请求缓存器,核心代码如下

import com.yishuifengxiao.common.crawler.cache.RequestCache;

public class CustomRequestCache implements RequestCache {

    /**
     * 将数据存储到指定的集合名中
     *
     * @param cacheName 缓存集合的名字
     * @param value     需要存储的值
     */
    @Override
    public void save(String cacheName, String value) {
      //自定义业务逻辑
    }

    /**
     * 先查找指定的值是否在集合中存在,然后将该值存储到此集合中
     *
     * @param cacheName 缓存集合的名字
     * @param value     需要存储的值
     * @return 如果存在则返回为true,否则为fasle
     */
    @Override
    public boolean lookAndCache(String cacheName, String value) {
        //自定义业务逻辑
        return false;
    }

    /**
     * 先查找指定的值是否在集合中存在
     *
     * @param cacheName 缓存集合的名字
     * @param value     需要存储的值
     * @return 如果存在则返回为true,否则为fasle
     */
    @Override
    public boolean exist(String cacheName, String value) {
        //自定义业务逻辑
        return false;
    }
    /**
     * 移除指定的缓存集合
     * @param cacheName 缓存集合的名字
     */
    @Override
    public void remove(String cacheName) {
        //自定义业务逻辑
    }

    /**
     * 获取指定缓存集合的成员数量
     * @param cacheName 缓存集合的名字
     * @return
     */
    @Override
    public long getCount(String cacheName) {
        //自定义业务逻辑
        return 0;
    }
}

2 应用自定义缓存器

        //获取风铃虫实例
        Crawler crawler = ...
        //注意此步骤一定要在风铃启动之前进行
        crawler.setRequestCache(new CustomRequestCache ())
        //启动风铃虫
        crawler.start();
Last Updated: 5/23/2020, 11:22:38 PM