springboot中 webmagic配置RedisScheduler实现分布式与去重

博客主要介绍了WebMagic配置RedisScheduler的相关内容。因JedisPool新版本中方法被弃用,排除jedis包用回旧版本。还涉及RedisConfig配置、配置文件设置以及Spider代码编写,强调注入JedisPool bean,且setUUID要放在setScheduler上面。

webmagic配置RedisScheduler

导包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<exclusions>
		<exclusion>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</exclusion>
	</exclusions>
</dependency>

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>

这里因为jedispool新版本中returnresource方法被弃用,所以将jedis包排除用回旧的版本。

配置RedisConfig

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;

    @Bean
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        return new JedisPool(jedisPoolConfig,host,port,timeout,password);
    }

}

配置文件

spring:
  redis:
    host: {主机号}
    port: {端口}
    password: {密码}
    timeout: 30000
    jedis:
      pool:
        max-idle: 100
        max-wait: 1000
server:
  port: 8081

spider代码

先注入我们在配置类中写好的JedisPool bean

@Autowired
    private JedisPool jedisPool;
Spider.create(new Processor())
                .setUUID("123456")
                .setScheduler(new RedisScheduler(jedisPool))
                .addUrl(url)
                .run();

setUUID只有在分布式的时候是必须的,当你在不同的项目中使用同样的uuid,他们就会使用redis中的同一个队列。所以setUUID必须放在setScheduler上面,不然获取不到uuid。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值