基于Spring Cloud的全自动化微信公众号消息采集系统-模块依赖和模块封装详解

基于Spring Cloud的全自动化微信公众号消息采集系统 前言 由于公司业务需求,需要获取客户提供的微信公众号的历史文章并每天进行更新,三百多个公众号显然不能通过人工去每天查看,问题提交到了IT组。对于热爱爬虫的我肯定要盘他,之前做过搜狗的微信爬虫,后来一直致力于java web了,这个项目又重新燃起了我对爬虫的热爱,第一次使用spring cloud架构来做爬虫,历时二十多天,终于搞定。接下来,我将通过一系列文章来分享此次项目经历,并奉上源码供大家指正! 一、系统简介 本系统是基于Java开发,可通过简单配置公众号名称或微信号,实现定时或即时抓取微信公众号 阅读详情

模块依赖关系和模块封装详解

前言

上一篇文章已经对大致对系统做了整体的分析,并简单介绍了每个模块的功能,本篇文章将详细介绍系统各个模块一些重要的功能实现。

一、版本选择

  • Springboot选用的版本是2.1.4,于是spring cloud选择的对应的G版本(Greenwich.RELEASE),一定要选择和Springboot版本对应的版本,否则项目无法正常启动,详细的对应关系可自行百度。
  • Nacos选用的是1.4,可自行到官网下载。
  • RocketMq测试环境安装的是window版,版本号4.3.0,安装可自行百度,单击版记得要改配置文件。
  • Redis版本为4.0。
  • Mysql建议5.7以上。
  • MongoDB建议4.0以上。
  • nginx选用1.18,支持websocket即可。

二、模块依赖关系

1、整体结构

父工程pom

	......
	<modules>
        <module>common-ws-starter</module>
        <module>pc-wx-spider</module>
        <module>java-wx-spider</module>
        <module>redis-ws-starter</module>
        <module>db-ws-starter</module>
        <module>sql-wx-spider</module>
        <module>rocketmq-ws-starter</module>
        <module>mobile-wx-spider</module>
    </modules>
    ......

截图展示:
在这里插入图片描述

2、依赖关系

starter结尾的都是自己封装的starter,spider结尾的是运行的springboot项目,不了解starter可先熟悉Springboot启动流程。

  • common-ws-starter
    不依赖其他模块
  • db-ws-starter
    不依赖其他模块
  • redis-ws-starter
    不依赖其他模块
  • rocketmq-ws-starter
    不依赖其他模块
  • sql-wx-spider
    依赖于common-ws-starter、com.wx.spider
		<!--集成公共模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>common-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--集成mysql模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>db-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
  • pc-wx-spider
    依赖于common-ws-starter、redis-ws-starter、rocketmq-ws-starter
 		<!--集成公共模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>common-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--集成redis模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>redis-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--集成mq模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>rocketmq-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
  • mobile-wx-spider
    依赖于common-ws-starter、redis-ws-starter、rocketmq-ws-starter
		<!--集成公共模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>common-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--集成redis模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>redis-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--集成mq模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>rocketmq-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
  • java-wx-spider
    依赖于common-ws-starter、rocketmq-ws-starter
		<!--集成公共模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>common-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--集成mq模块-->
        <dependency>
            <groupId>com.wx.spider</groupId>
            <artifactId>rocketmq-ws-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

三、功能模块详解

本节对模块里一些重点功能加以说明。

1、common-ws-starter

公用模块主要放一些model、pojo、vo、util等,同时供多个模块使用,是在util中封装了一些系统的定制功能,比如解析抓包返回的json,并没有难理解的地方。值得注意的是Mongo和mysql对应的实体类需要在字段上加注解,则需要在pom.xml中导入响应坐标,其他模块引入的时候需要排除springboot默认的自动装配功能,否则自己封装后可能启动失败。

2、db-ws-starter

自定义数据源模块,此模块通过自定义注解和AOP实现了多数据源动态切换,此模块并无任何业务逻辑,虽然mybatis-plus有自带动态数据源功能注解,但灵活性不强,于是自己封装数据为后期加分布式事务和分库分表做准备。

枚举限定数据源名称

package com.wx.spider.db.constant;

/**
 * @author:feng
 * @create:2021-04-16 15:59
 */
public enum DataSourceKey {
    core, sec
}

这里可配置多个数据源,需根据自己业务而定,目前配置两个,需要和bootstrap.yml中的配置对应。

自定义注解@DataSource,并配置切面

在业务逻辑类中加入此注解可自动去操作name属性对应的数据源。

package com.wx.spider.db.annotation;

import java.lang.annotation.*;

/**
 * @author:feng
 * @create:2021-04-16 15:54
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    //数据库名称
    String name();
}

切面的实现:

package com.wx.spider.db.aop;

import com.wx.spider.db.annotation.DataSource;
import com.wx.spider.db.constant.DataSourceKey;
import com.wx.spider.db.uitl.DataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;

/**
 * @author:feng
 * @create:2021-04-16 15:55
 */
@Slf4j
@Aspect
@Order(-1) // 保证该AOP在@Transactional之前执行
public class DataSourceAOP {


    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, DataSource ds) throws Throwable {
        String dsId = ds.name();
        try {
            DataSourceKey dataSourceKey = DataSourceKey.valueOf(dsId);
            DataSourceHolder.setDataSourceKey(dataSourceKey);
        } catch (Exception e) {
            log.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature());
        }
    }


    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, DataSource ds) {
        log.debug("Revert DataSource : {transIdo} > {}", ds.name(), point.getSignature());
        DataSourceHolder.clearDataSourceKey();
    }

}
package com.wx.spider.db.uitl;

import com.wx.spider.db.constant.DataSourceKey;

/**
 * @author:feng
 * @create:2021-04-16 16:00
 */
public class DataSourceHolder {

    //注意使用ThreadLocal,微服务下游建议使用信号量
    private static final ThreadLocal<DataSourceKey> dataSourceKey = new ThreadLocal<>();

    //得到当前的数据库连接
    public static DataSourceKey getDataSourceKey() {
        return dataSourceKey.get();
    }
    //设置当前的数据库连接
    public static void setDataSourceKey(DataSourceKey type) {
        dataSourceKey.set(type);
    }
    //清除当前的数据库连接
    public static void clearDataSourceKey() {
        dataSourceKey.remove();
    }


}
package com.wx.spider.db.uitl;

import com.wx.spider.db.constant.DataSourceKey;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:feng
 * @create:2021-04-16 16:00
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private Map<Object, Object> datasources;

    public DynamicDataSource() {
        datasources = new HashMap<>();

        super.setTargetDataSources(datasources);

    }

    public <T extends DataSource> void addDataSource(DataSourceKey key, T data) {
        datasources.put(key, data);
    }

    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSourceKey();
    }

}

通过META-INF/spring.factories配置自动装配

spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.wx.spider.db.DataSourceAutoConfig

DataSourceAutoConfig:

package com.wx.spider.db;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.wx.spider.db.aop.DataSourceAOP;
import com.wx.spider.db.constant.DataSourceKey;
import com.wx.spider.db.uitl.DynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author:feng
 * @create:2021-04-16 15:54
 */
@Configuration
@Import(DataSourceAOP.class)
@AutoConfigureBefore(value={DruidDataSourceAutoConfigure.class, MybatisPlusAutoConfiguration.class})
@ConditionalOnProperty(name = {"spring.datasource.dynamic.enable"}, matchIfMissing = false, havingValue = "true")
public class DataSourceAutoConfig {


    //	创建数据源
//	所有引入db-core的模块都需要一个核心库
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.core")
    public DataSource dataSourceCore(){
        return DruidDataSourceBuilder.create().build();
    }
    //	第二个数据源
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.sec")
    public DataSource dataSourceSec(){
        return DruidDataSourceBuilder.create().build();
    }


    @Primary
    @Bean // 只需要纳入动态数据源到spring容器
    public DataSource dataSource() {
        System.out.println("--------------------------------动态数据源-------------------------------------");
        DynamicDataSource dataSource = new DynamicDataSource();
        DataSource coreDataSource =  dataSourceCore() ;
        DataSource logDataSource =  dataSourceSec();
        dataSource.addDataSource(DataSourceKey.core, coreDataSource);
        dataSource.addDataSource(DataSourceKey.sec, logDataSource);
        dataSource.setDefaultTargetDataSource(coreDataSource);
        return dataSource;
    }

    @Bean // 将数据源纳入spring事物管理
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource")  DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

注解解释:

  • 将切面导入(@Import(DataSourceAOP.class));
  • 在加载自带数据源之前进行装配@AutoConfigureBefore(value={DruidDataSourceAutoConfigure.class, MybatisPlusAutoConfiguration.class});
  • 可灵活配置是否启用次加载(@ConditionalOnProperty(name = {“spring.datasource.dynamic.enable”}, matchIfMissing = false, havingValue = “true”))。

3、redis-ws-starter

此模块是对spring-boot-starter-data-redis的二次封装,提供便捷的Redis工具类和Redisson工具类,同时还可使用spring-boot-starter-data-redis提供的操作类StringRedisTemplate和RedisTemplate,兼容单机版、集群版和哨兵版的配置。
核心类:

package com.wx.spider.redis;

import com.wx.spider.redis.serizlizer.RedisObjectSerializer;
import com.wx.spider.redis.util.RedisUtil;
import io.lettuce.core.RedisClient;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Sentinel;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
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.*;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.ReflectionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.*;

/**
 * @author:feng
 * @create:2021-04-14 16:29
 */
@Configuration
@EnableCaching
@SuppressWarnings("all")
@AutoConfigureBefore(RedisTemplate.class)
@EnableConfigurationProperties(RedissonProperties.class)
public class RedisAutoConfig {

    @Autowired(required = false)
    private RedissonProperties redissonProperties;

    @Autowired
    private RedisProperties redisProperties;

    @Autowired
    private ApplicationContext ctx;

    @Bean(destroyMethod = "destroy")
    @ConditionalOnClass(RedisClient.class)
    public LettuceConnectionFactory lettuceConnectionFactory(GenericObjectPoolConfig genericObjectPoolConfig) {
        Method clusterMethod = ReflectionUtils.findMethod(RedisProperties.class, "getCluster");
        Method timeoutMethod = ReflectionUtils.findMethod(RedisProperties.class, "getTimeout");
        Object timeoutValue = ReflectionUtils.invokeMethod(timeoutMethod, redisProperties);
        RedisConfiguration redisConfiguration = null;
        LettuceClientConfiguration clientConfig = null;
        if (redisProperties.getSentinel() != null) {
            // 哨兵配置
            Method nodesMethod = ReflectionUtils.findMethod(Sentinel.class, "getNodes");
            Object nodesValue = ReflectionUtils.invokeMethod(nodesMethod, redisProperties.getSentinel());

            String[] nodes = null;
            Set<String> sentinelHostAndPorts = new HashSet<>();
            if (nodesValue instanceof String) {
                nodes = convert(Arrays.asList(((String) nodesValue).split(",")));
                sentinelHostAndPorts.addAll(Arrays.asList(((String) nodesValue).split(",")));
            } else {
                nodes = convert((List<String>) nodesValue);
                sentinelHostAndPorts.addAll((List<String>) nodesValue);
            }
            redisConfiguration = new RedisSentinelConfiguration(redisProperties.getSentinel().getMaster(),
                    sentinelHostAndPorts);
            ((RedisSentinelConfiguration) redisConfiguration)
                    .setPassword(RedisPassword.of(redisProperties.getPassword()));
            ((RedisSentinelConfiguration) redisConfiguration).setDatabase(redisProperties.getDatabase());
            clientConfig = LettucePoolingClientConfiguration.builder().commandTimeout(redisProperties.getTimeout())
                    .poolConfig(genericObjectPoolConfig).build();

        } else if (clusterMethod != null && ReflectionUtils.invokeMethod(clusterMethod, redisProperties) != null) {
            // 集群配置
            List<String> clusterNodes = redisProperties.getCluster().getNodes();
            Set<RedisNode> nodes = new HashSet<RedisNode>();
            clusterNodes.forEach(address -> nodes
                    .add(new RedisNode(address.split(":")[0].trim(), Integer.valueOf(address.split(":")[1]))));
            redisConfiguration = new RedisClusterConfiguration();
            ((RedisClusterConfiguration) redisConfiguration).setClusterNodes(nodes);
            ((RedisClusterConfiguration) redisConfiguration)
                    .setPassword(RedisPassword.of(redisProperties.getPassword()));

            /**
             * ClusterTopologyRefreshOptions配置用于开启自适应刷新和定时刷新。如自适应刷新不开启,
             * Redis集群变更时将会导致连接异常!
             */
            ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                    // 开启自适应刷新
                    .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT,
                            ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS)
                    // 开启所有自适应刷新,MOVED,ASK,PERSISTENT都会触发
                    // .enableAllAdaptiveRefreshTriggers()
                    // 自适应刷新超时时间(默认30秒)
                    .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(25)) // 默认关闭开启后时间为30秒
                    // 开周期刷新
                    .enablePeriodicRefresh(Duration.ofSeconds(20)) // 默认关闭开启后时间为60秒
                    // ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD
                    // 60 .enablePeriodicRefresh(Duration.ofSeconds(2)) =
                    // .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
                    .build();
            clientConfig = LettucePoolingClientConfiguration.builder().commandTimeout(redisProperties.getTimeout())
                    .poolConfig(genericObjectPoolConfig)
                    .clientOptions(
                            ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build())
                    // 将appID传入连接,方便Redis监控中查看
                    // .clientName(appName + "_lettuce")
                    .build();

        } else {
            // 单机版配置
            redisConfiguration = new RedisStandaloneConfiguration();
            ((RedisStandaloneConfiguration) redisConfiguration).setDatabase(redisProperties.getDatabase());
            ((RedisStandaloneConfiguration) redisConfiguration).setHostName(redisProperties.getHost());
            ((RedisStandaloneConfiguration) redisConfiguration).setPort(redisProperties.getPort());
            ((RedisStandaloneConfiguration) redisConfiguration)
                    .setPassword(RedisPassword.of(redisProperties.getPassword()));

            clientConfig = LettucePoolingClientConfiguration.builder().commandTimeout(redisProperties.getTimeout())
                    .poolConfig(genericObjectPoolConfig).build();

        }

        if (redisProperties.isSsl()) {
            clientConfig.isUseSsl();
        }

        LettuceConnectionFactory factory = new LettuceConnectionFactory(redisConfiguration, clientConfig);
        return factory;
    }

    /**
     * GenericObjectPoolConfig 连接池配置
     */
    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
        poolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
        poolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
        poolConfig.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().getSeconds());
        Duration timeOut = redisProperties.getTimeout();
        Duration shutdownTimeout = redisProperties.getLettuce().getShutdownTimeout();
        return poolConfig;
    }


    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory ) {

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) // 设置缓存的默认超时时间:30分钟
                .disableCachingNullValues() // 如果是空值,不缓存
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string())) // 设置key序列化器
                .serializeValuesWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.java())); // 设置value序列化器
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(lettuceConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

    /**
     * 适配redis cluster单节点
     */
//    @Primary
//    @Bean("redisTemplate")
    // 没有此属性就不会装配bean 如果是单个redis 将此注解注释掉
//    @ConditionalOnProperty(name = "spring.redis.cluster.nodes", matchIfMissing = false)
    public RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        // RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
        RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
        redisTemplate.setKeySerializer(stringSerializer); // key的序列化类型
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(redisObjectSerializer); // value的序列化类型
        redisTemplate.setHashValueSerializer(redisObjectSerializer); // value的序列化类型
        redisTemplate.afterPropertiesSet();

        redisTemplate.opsForValue().set("hello", "wolrd");
        return redisTemplate;
    }

    /**
     * 适配redis单节点
     */
    @Primary
    @Bean("redisTemplate")
    @ConditionalOnProperty(name = "spring.redis.host", matchIfMissing = true)
    public RedisTemplate<String, Object> getSingleRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // key的序列化类型
        redisTemplate.setValueSerializer(redisObjectSerializer); // value的序列化类型
        redisTemplate.setHashValueSerializer(redisObjectSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public HashOperations<String, String, String> hashOperations(StringRedisTemplate stringRedisTemplate) {
        return stringRedisTemplate.opsForHash();
    }

    /**
     * redis工具类
     */
    @Bean("redisUtil")
    public RedisUtil redisUtil(LettuceConnectionFactory lettuceConnectionFactory,
                               StringRedisTemplate stringRedisTemplate, HashOperations<String, String, String> hashOperations) {
        RedisUtil redisUtil = new RedisUtil(lettuceConnectionFactory, stringRedisTemplate, hashOperations);
        return redisUtil;
    }

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(name = "spring.redis.redisson.enable", matchIfMissing = false, havingValue = "true")
    @ConditionalOnMissingBean(RedissonClient.class)
    public RedissonClient redissonClient() throws IOException {
        Config config = null;
        Method clusterMethod = ReflectionUtils.findMethod(RedisProperties.class, "getCluster");
        Method timeoutMethod = ReflectionUtils.findMethod(RedisProperties.class, "getTimeout");
        Object timeoutValue = ReflectionUtils.invokeMethod(timeoutMethod, redisProperties);
        int timeout;
        if (null == timeoutValue) {
            timeout = 60000;
        } else if (!(timeoutValue instanceof Integer)) {
            Method millisMethod = ReflectionUtils.findMethod(timeoutValue.getClass(), "toMillis");
            timeout = ((Long) ReflectionUtils.invokeMethod(millisMethod, timeoutValue)).intValue();
        } else {
            timeout = (Integer) timeoutValue;
        }
        // spring.redis.redisson.config=classpath:redisson.yaml
        if (redissonProperties.getConfig() != null) {

            try {
                InputStream is = getConfigStream();
                config = Config.fromJSON(is);
            } catch (IOException e) {
                // trying next format
                try {
                    InputStream is = getConfigStream();
                    config = Config.fromYAML(is);
                } catch (IOException ioe) {
                    throw new IllegalArgumentException("Can't parse config", ioe);
                }
            }
        } else if (redisProperties.getSentinel() != null) {
            // 哨兵配置
            Method nodesMethod = ReflectionUtils.findMethod(Sentinel.class, "getNodes");
            Object nodesValue = ReflectionUtils.invokeMethod(nodesMethod, redisProperties.getSentinel());

            String[] nodes;
            if (nodesValue instanceof String) {
                nodes = convert(Arrays.asList(((String) nodesValue).split(",")));
            } else {
                nodes = convert((List<String>) nodesValue);
            }

            config = new Config();
            config.useSentinelServers().setMasterName(redisProperties.getSentinel().getMaster())
                    .addSentinelAddress(nodes).setDatabase(redisProperties.getDatabase()).setConnectTimeout(timeout)
                    .setPassword(redisProperties.getPassword());
        } else if (clusterMethod != null && ReflectionUtils.invokeMethod(clusterMethod, redisProperties) != null) {
            // 集群配置
            Object clusterObject = ReflectionUtils.invokeMethod(clusterMethod, redisProperties);
            Method nodesMethod = ReflectionUtils.findMethod(clusterObject.getClass(), "getNodes");
            List<String> nodesObject = (List) ReflectionUtils.invokeMethod(nodesMethod, clusterObject);
            String[] nodes = convert(nodesObject);
            config = new Config();
            config.useClusterServers().addNodeAddress(nodes).setConnectTimeout(timeout)
                    .setPassword(redisProperties.getPassword());
        } else {
            // 单机redssion默认配置
            config = new Config();
            String prefix = "redis://";
            Method method = ReflectionUtils.findMethod(RedisProperties.class, "isSsl");
            if (method != null && (Boolean) ReflectionUtils.invokeMethod(method, redisProperties)) {
                prefix = "rediss://";
            }

            config.useSingleServer().setAddress(prefix + redisProperties.getHost() + ":" + redisProperties.getPort())
                    .setConnectTimeout(timeout).setDatabase(redisProperties.getDatabase())
                    .setPassword(redisProperties.getPassword());

        }

        return Redisson.create(config);
    }

    private String[] convert(List<String> nodesObject) {
        List<String> nodes = new ArrayList<String>(nodesObject.size());
        for (String node : nodesObject) {
            if (!node.startsWith("redis://") && !node.startsWith("rediss://")) {
                nodes.add("redis://" + node);
            } else {
                nodes.add(node);
            }
        }
        return nodes.toArray(new String[nodes.size()]);
    }

    private InputStream getConfigStream() throws IOException {
        Resource resource = ctx.getResource(redissonProperties.getConfig());
        InputStream is = resource.getInputStream();
        return is;
    }

}

4、rocketmq-ws-starter

此模块是对rocketmq-spring-boot-starter的二次封装,由于自带的封装的消费者没有带获取消费重试次数功能,于是自己做了封装,因为爬虫时会有很多不定性因素导致失败,以便于屡次消费失败后记录错误日志。
核心代码:
通过自定义注解配置消费者模式和主题、线程数量等。

package com.wx.spider.rocketmq.annotation;

import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.lang.annotation.*;

/**
 * @author:feng
 * @create:2021-04-21 15:17
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WsRocketMQConsumer {

    String consumerGroup() default "";

    String topic();

    String selectorExpression() default "*";

    int consumeThreadMax() default 32;

    int consumeThreadMin() default 8;

    int consumeMessageBatchMaxSize() default 1;

    String nameServer() default "";

    MessageModel messageModel() default MessageModel.CLUSTERING;

}

通过继承抽象类来创建消费者监听,自己可加入业务逻辑并且可以通过MessageExt获取消费次数。

package com.wx.spider.rocketmq.consumer;

import com.wx.spider.rocketmq.annotation.WsRocketMQConsumer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;

/**
 * @author:feng
 * @create:2021-04-21 12:21
 * 消费者抽象类
 */
@Slf4j
public abstract class BaseRocketMQConsumer {
    @Value("${rocketmq.name-server}")
    private String namesrvAddr;
    @Value("${rocketmq.consumer.group}")
    private String groupName;

    @PostConstruct
    public void init() {

        WsRocketMQConsumer annotation = this.getClass().getAnnotation(WsRocketMQConsumer.class);
        String nameServer = annotation.nameServer();
        if(nameServer != null && !"".equals(nameServer)){
            namesrvAddr = nameServer;
        }
        String consumerGroup = annotation.consumerGroup();
        if(consumerGroup != null && !"".equals(consumerGroup)){
            groupName = consumerGroup;
        }

        String topicStr = annotation.topic();

        String selectorExpression = annotation.selectorExpression();

        int consumeThreadMin = annotation.consumeThreadMin();
        int consumeThreadMax = annotation.consumeThreadMax();
        MessageModel messageModel = annotation.messageModel();

        int consumeMessageBatchMaxSize = annotation.consumeMessageBatchMaxSize();

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(groupName);
        consumer.setNamesrvAddr(namesrvAddr);
        consumer.setConsumeThreadMin(consumeThreadMin);
        consumer.setConsumeThreadMax(consumeThreadMax);
        consumer.setMessageModel(messageModel);
        try {
            consumer.subscribe(topicStr, selectorExpression);
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
            consumer.registerMessageListener((MessageListenerConcurrently) (list, consumeOrderlyContext) -> {
                try {
                    for (MessageExt messageExt : list) {
                        String tag = messageExt.getTags();
                        String topic = messageExt.getTopic();
                        return consume(tag, topic, messageExt);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //稍后再试
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                //消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            });
            consumer.setConsumeMessageBatchMaxSize(consumeMessageBatchMaxSize);
            consumer.start();
            System.out.println("消费者启动完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    protected abstract ConsumeConcurrentlyStatus consume(String tag, String topic, MessageExt messageExt);

}

总结

本篇文章对模块之间的关系和功能模块(starter)的封装做了解释说明,项目的功能结构大概已经明了,之后的文章将进入业务逻辑篇,介绍是如何通过抓包和js注入获取自动获取文章信息的。

计算机组成原理实验二 运算器组成实验 事实上,ALU的设计是在全加器的基础上,对全加器功能的扩展来实现符合要求的多种算术/逻辑运算的功能。为了实现多种功能的运算,An、Bn数据是不能直接与全加器相连接的,它们受到功能变量F3—F1的制约,因此,可由An、Bn数据和功能变量F3-F1组合成新的函数Xn 、Yn,然后,再将Xn 、Yn和下一位进位Cn-1通过全加器进行全加运算以实现所需的运算功能。AC寄存器可用来存储ALU的输入以实现两个操作数的运算操作,也可以用来存储来自ALU的结果,以将这些结果反馈给ALU以进行更多的处理。 阅读详情

相关推荐

从‘全步’到‘微步’:一张图看懂步进电机细分控制,选对模式让你的项目更丝滑

本文深入解析步进电机细分控制技术,从全步到微步的演进过程,帮助工程师根据项目需求选择最优控制模式。通过对比不同细分等级的性能特点和应用场景,提供3D打印、实验室自动化等领域的黄金配置方案,实现更精准、平稳的电机控制效果。

weixin_29290259的博客 475

大道至简 - 大型电商平台从架构剖析设计到功能实现全程实录

本课程从无到有,搭建一个简易版的电商平台,并从不同角度分析设计此项目各个主要模块和功能点,将会应用到除迭代器模式以外的所有GoF设计模式,旨在演示设计模式在项目中的实际应用,以及如何针对不同情况进行功能设计,希望可以帮助大家敲开设计之门。

Python爬虫实战:5分钟搞定Web of Science文献批量导出与解析(附完整代码)

本文提供了一套利用Python爬虫技术,快速实现Web of Science文献批量提取与解析的完整方案。通过解析官方导出的HTML文件,结合BeautifulSoup和pandas库,可将文献数据自动转换为结构化的Excel/CSV表格,帮助科研人员高效管理文献信息,节省大量手动整理时间。

weixin_29050513的博客 1183

【微信开发第二章】SpringBoot实现微信公众号普通消息和模板消息回复

在进行微信公众号业务开发的时候,微信公众号的消息回复是非常重要的一环,而微信公众号消息回复分为:普通消息自动回复和模板消息回复。该篇文章会先使用微信测试工具过一遍流程,再使用代码进行实现,**并且每一步都有记录,力争理解的同时各位小伙伴也能够实现功能**

weixin_47316183的博客 4994

FIddler+Proxifer 实现PC客户端抓包详细教程

FIddler+Proxifer 实现PC客户端抓包详细教程

森明帮大于黑虎帮的博客 1万+

无需云服务器:飞牛云NAS+Docker搭建本地WordPress站点全球访问

在数字化浪潮中,网站搭建已成为个人和企业在推广自身品牌与业务的首要选择。飞牛云新推出的fnOS,这款集多功能于一身的nas系统,以其卓越的性能和灵活性,成为理想的本地网站部署平台。本文将带你一探如何在飞牛云NAS上通过Docker部署WordPress,并利用cpolar实现全球访问。

LT15171009269的博客 6538

springboot 实现微信公众号的模板消息推送

一、微信公众号测试平台 地址: http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index 需要数据1 需要数据2 发送消息模板可不配置公众号对接相关功能,直接使用openId 发送模板信息功能即可,openId 可让用户关注公众号录入系统, 或者在公众号添加h5 表单,绑定系统账号, 微信打开的h5 页面可获取当前用户的openId 二、实现代码 1、yml 配置 ## 微信公众号 相关配置

ws - 兮的博客空间 1万+

基于STM32、HAL库的MICRF112YMM-TR 无线收发器驱动程序设计

内部集成了 VCO、PLL、PA、LNA、混频器、滤波器等射频功能单元,极大减少了外部元件数量,降低了设计和布线难度。: 具有多种工作模式(睡眠、待机、接收、发射),待机电流极低,非常适合电池供电的物联网(IoT)设备。是 Microchip 公司生产的一款高性能、低功耗的单片 UHF ASK/FSK 收发器芯片。: 支持 ASK (幅移键控) 和 FSK (频移键控) 调制,适应不同应用需求。// 可以添加其他配置参数,如中心频率、数据速率等。智能家居(安防、遥控、传感)远程钥匙进入系统 (RKE)

corlin6688的博客 423

基于SpringBoot微信公众号的开发

注册开发者微信公众号; natapp内外网穿透技术; 如何科学的翻墙获取学习资料; 如何获取公众号唯一的token; 开发公众号遇到的诸多问题及解决方法; 使用测试公众号学习众多的接口调用;

东风麦芽糖 8628

MounRiver Studio(MRS)使用技巧:添加头文件目录;增加代码分组

MounRiver Studio(MRS)使用技巧:添加头文件目录

cheng___yi的博客 1817

2025华为杯第二十二届中国研究生数学建模竞赛D题:低空湍流监测及最优航路规划 - 完整解题分析+完整MATLAB源码!(上篇)

🎓 本文收录于 《滚雪球学数学建模》专栏,本专栏专注于从零基础出发,带你循序渐进掌握数学建模的核心方法与思维路径。通过“滚雪球式”学习法,从最简单的生活化案例到经典建模工具,再到省赛、国赛真题实战演练,逐步积累知识与技能,帮助你搭建完整的建模体系。无论你是刚接触建模的新生,还是希望提升科研与竞赛能力的学者与工程师,本专栏都将为你提供一条清晰、高效、可实操的建模成长路线,助力你快速进阶,突破难点,迈向数学建模竞赛与实际应用的更高峰 🚀!

**My Coding Family** 2601

Java SpringBoot 集成微信公众号

Java、SpringBoot集成微信公众号

AstarCloud 1939

10天冲刺国自然基金!用这套实战AI提示词指令教程,助你中标率翻倍!亲测DeepSeek和ChatGPT不好用

虽然以上国自然提示词指令经过反复实测,但并不是万能无脑帮你搞定所有,大模型AI的特性是你专业领域能力越强,它的智商表现就会更加强大,通过以上提示词教程的使用,大大提升中标概率是肯定的。还有就是大模型的使用上,不是市面上大家都说好的就一定适用,目前来看,Gemini和Claude的两个模型是非常适合国自然本子的修改的。在使用大模型进行国自然本子撰写修改时,首先是角色的设定,然后是目标和背景的描述,好用的提示词指令都是要经过无数次的实测,比对输出结果后又反复调整,达到最佳的效果状态的提示词指令。

智能AI让学术科研更容易 1263

基于Spring Cloud的全自动化微信公众号消息采集系统-PC端采集列表

前言 前面两篇文章介绍了系统流程和功能模块的封装,这篇文章将对消息列表的采集做以说明,此篇文章中注重思路而不是技术和源码,逻辑的代码千篇一律,可靠的算法万里挑一。 准备工作 1、采集来源 研究发现公众号文章访问获取的渠道有多种: 搜狗搜索:只能获取前10条; 公众号历史消息页,24H内公众号有次数限制(目前发现200+次数,不同微信号可能有所不同); 微信公众平台写图文消息引用其他公众号文章的查询接口,频繁后会限制查询,并且; ...

qf_java的博客 528

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Spring Cloud 每个组件的原理详解

我们先认识一下SpringCloud的各个组件,然后知其所以然。 关注微信公众号 Java后端,后台输入命令 666 下载技术手册。 原理讲解前,先看一个最经典的业务场景,如开发一个电商网站,要实现支付订单的功能,流程如下: 1、创建一个订单之后,如果用户立刻支付了这个订单,我们需要将订单状态更新为“已支付” 2、扣减相应的商品库存 3、通知仓储中心,进行发货 4、给用户的这次购物增加相应的积分 如上,微服务的应用场景和核心竞争力: 降低耦合:每一个微服务专注于单一功能,并通过定义良好的

spring_root的博客 554

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

基于 Spring Cloud +OAuth2 的权限管理系统

分享一个强大权限管理系统,可快速构建微服务代码框架。基于 Spring Cloud Hoxton 、Spring Boot 2.3、 OAuth2 的RBAC权限管理系统,数据驱动视图...

公众号:逛逛GitHub 362

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Kustomize 术语表:理解 Kubernetes YAML 声明式配置定制中的核心概念

Kustomize 是一套面向 Kubernetes 的"模板无关、结构化定制"工具,围绕它形成了 `kustomization`、`base`、`overlay`、`variant`、`patch` 等一整套专属术语。本文以仓库中的官方术语表([site/content/en/docs/Reference/glossary.md](https://link.gitcode.com/i/17d0f

gitblog_00708的博客 1042

Spring Cloud架构各组件的原理分析

作者|白羽毛作者|toutiao.com/i6888099913867985422/我们先认识一下SpringCloud的各个组件,然后知其所以然。关注微信公众号 肉眼品世界,后台输入命...

weixin_45727359的博客 616
上一篇: 基于Spring Cloud的全自动化微信公众号消息采集系统
下一篇: 基于Spring Cloud的全自动化微信公众号消息采集系统-PC端采集列表
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址