• 猿创征文 | 项目整合KafkaStream实现文章热度实时计算


    8420b26844034fab91b6df661ae68671.png

     个人简介: 

    > 📦个人主页:赵四司机
    > 🏆学习方向:JAVA后端开发 
    > ⏰往期文章:SpringBoot项目整合微信支付
    > 🔔博主推荐网站:牛客网 刷题|面试|找工作神器
    > 📣种一棵树最好的时间是十年前,其次是现在!
    > 💖喜欢的话麻烦点点关注喔,你们的支持是我的最大动力。

    前言:

    最近在做一个基于SpringCloud+Springboot+Docker的新闻头条微服务项目,用的是黑马的教程,现在项目开发进入了尾声,我打算通过写文章的形式进行梳理一遍,并且会将梳理过程中发现的Bug进行修复,有需要改进的地方我也会继续做出改进。这一系列的文章我将会放入微服务项目专栏中,这个项目适合刚接触微服务的人作为练手项目,假如你对这个项目感兴趣你可以订阅我的专栏进行查看,需要资料可以私信我,当然要是能给我点个小小的关注就更好了,你们的支持是我最大的动力。

    如果你想要一个可以系统学习的网站,那么我推荐的是牛客网,个人感觉用着还是不错的,页面很整洁,而且内容也很全面,语法练习,算法题练习,面试知识汇总等等都有,论坛也很活跃,传送门链接:牛客刷题神器

    目录

    一:Springboot集成Kafka Stream

    1.设置配置类信息

    2.修改application.yml文件

    3.新增配置类,创建KStream对象,进行聚合

    二:热点文章实时计算

    1.实现思路

    2.环境搭建

    2.1:在文章微服务中集成Kafka生产者配置

    2.2:记录用户行为

    2.3:定义Stream实现消息接收并聚合

    2.4:重新计算文章分值并更新Redis缓存数据

    2.5:设置监听类

    三:功能测试


    一:Springboot集成Kafka Stream

    1.设置配置类信息

    1. package com.my.kafka.config;
    2. import lombok.Getter;
    3. import lombok.Setter;
    4. import org.apache.kafka.common.serialization.Serdes;
    5. import org.apache.kafka.streams.StreamsConfig;
    6. import org.springframework.boot.context.properties.ConfigurationProperties;
    7. import org.springframework.context.annotation.Bean;
    8. import org.springframework.context.annotation.Configuration;
    9. import org.springframework.kafka.annotation.EnableKafkaStreams;
    10. import org.springframework.kafka.annotation.KafkaStreamsDefaultConfiguration;
    11. import org.springframework.kafka.config.KafkaStreamsConfiguration;
    12. import java.util.HashMap;
    13. import java.util.Map;
    14. /**
    15. * 通过重新注册KafkaStreamsConfiguration对象,设置自定配置参数
    16. */
    17. @Setter
    18. @Getter
    19. @Configuration
    20. @EnableKafkaStreams
    21. @ConfigurationProperties(prefix="kafka")
    22. public class KafkaStreamConfig {
    23. private static final int MAX_MESSAGE_SIZE = 16* 1024 * 1024;
    24. private String hosts;
    25. private String group;
    26. @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
    27. public KafkaStreamsConfiguration defaultKafkaStreamsConfig() {
    28. Map props = new HashMap<>();
    29. props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, hosts);
    30. props.put(StreamsConfig.APPLICATION_ID_CONFIG, this.getGroup()+"_stream_aid");
    31. props.put(StreamsConfig.CLIENT_ID_CONFIG, this.getGroup()+"_stream_cid");
    32. props.put(StreamsConfig.RETRIES_CONFIG, 10);
    33. props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    34. props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
    35. return new KafkaStreamsConfiguration(props);
    36. }
    37. }

            可能你会有这样的疑问,前面介绍Kafka时候不是直接在yml文件里面设置参数就行了吗?为什么这里还要自己写配置类呢?是因为Spring对KafkaStream的集成并不是很好,所以我们才需要自己去写配置类信息。需要注意的一点是,配置类中必须添加@EnableKafkaStreams这一注解。

    2.修改application.yml文件

    1. kafka:
    2. hosts: 192.168.200.130:9092
    3. group: ${spring.application.name}

    3.新增配置类,创建KStream对象,进行聚合

    1. package com.my.kafka.stream;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.apache.kafka.streams.KeyValue;
    4. import org.apache.kafka.streams.StreamsBuilder;
    5. import org.apache.kafka.streams.kstream.KStream;
    6. import org.apache.kafka.streams.kstream.TimeWindows;
    7. import org.apache.kafka.streams.kstream.ValueMapper;
    8. import org.springframework.context.annotation.Bean;
    9. import org.springframework.context.annotation.Configuration;
    10. import java.time.Duration;
    11. import java.util.Arrays;
    12. @Slf4j
    13. @Configuration
    14. public class KafkaStreamHelloListener {
    15. @Bean
    16. public KStream kStream(StreamsBuilder streamsBuilder){
    17. //创建KStream对象,同时指定从那个topic中接收消息
    18. KStream stream = streamsBuilder.stream("itcast-topic-input");
    19. stream.flatMapValues((ValueMapper>) value -> Arrays.asList(value.split(" ")))
    20. //根据value进行聚合分组
    21. .groupBy((key,value)->value)
    22. //聚合计算时间间隔
    23. .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
    24. //求单词的个数
    25. .count()
    26. .toStream()
    27. //处理后的结果转换为string字符串
    28. .map((key,value)->{
    29. System.out.println("key:"+key+",value:"+value);
    30. return new KeyValue<>(key.key().toString(),value.toString());
    31. })
    32. //发送消息
    33. .to("itcast-topic-out");
    34. return stream;
    35. }
    36. }

            这里实现的功能还是计算单词个数,假如你有其他计算需求你可以更改里面的逻辑代码以符合你的需求。该类可注入StreamBuilder,其返回值必须是KStream且放入Spring容器中(添加了@Bean注解)。

    二:热点文章实时计算

    1.实现思路

            实现思路很简单,当用户有点赞、收藏、阅读等行为记录时候,就将消息发送给Kafka进行流式处理,随后Kafka再进行聚合并重新计算文章分值,除此之外还需要更新数据库中的数据。需要注意的是,按常理来说当天的文章热度权重是要比非当天的文章热度权重大的,因此当日文章的热度权重需要乘以3,随后查询Redis中的数据,假如该文章分数大于Redis中最低分文章,这时候就需要进行替换操作,更新Redis数据。 

    2.环境搭建

    2.1:在文章微服务中集成Kafka生产者配置

    (1)修改nacos,增加内容:

    1. kafka:
    2. bootstrap-servers: 49.234.52.192:9092
    3. producer:
    4. retries: 10
    5. key-serializer: org.apache.kafka.common.serialization.StringSerializer
    6. value-serializer: org.apache.kafka.common.serialization.StringSerializer
    7. hosts: 49.234.52.192:9092
    8. group: ${spring.application.name}

    (2)定义相关实体类、常量

    1. package com.my.model.mess;
    2. import lombok.Data;
    3. @Data
    4. public class UpdateArticleMess {
    5. /**
    6. * 修改文章的字段类型
    7. */
    8. private UpdateArticleType type;
    9. /**
    10. * 文章ID
    11. */
    12. private Long articleId;
    13. /**
    14. * 修改数据的增量,可为正负
    15. */
    16. private Integer add;
    17. public enum UpdateArticleType{
    18. COLLECTION,COMMENT,LIKES,VIEWS;
    19. }
    20. }

    2.2:记录用户行为

    1. @Autowired
    2. private KafkaTemplate kafkaTemplate;
    3. /**
    4. * 读文章行为记录(阅读量+1)
    5. * @param map
    6. * @return
    7. */
    8. public ResponseResult readBehavior(Map map) {
    9. if(map == null || map.get("articleId") == null) {
    10. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    11. }
    12. Long articleId = Long.parseLong((String) map.get("articleId"));
    13. ApArticle apArticle = getById(articleId);
    14. if(apArticle != null) {
    15. //获取文章阅读数
    16. Integer views = apArticle.getViews();
    17. if(views == null) {
    18. views = 0;
    19. }
    20. //调用Kafka发送消息
    21. UpdateArticleMess mess = new UpdateArticleMess();
    22. mess.setArticleId(articleId);
    23. mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
    24. mess.setAdd(1);
    25. kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
    26. //更新文章阅读数
    27. LambdaUpdateWrapper luw = new LambdaUpdateWrapper<>();
    28. luw.eq(ApArticle::getId,articleId);
    29. luw.set(ApArticle::getViews,views + 1);
    30. update(luw);
    31. }
    32. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    33. }
    34. /**
    35. * 用户点赞
    36. * @param map
    37. * @return
    38. */
    39. @Override
    40. public ResponseResult likesBehavior(Map map) {
    41. if(map == null || map.get("articleId") == null) {
    42. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    43. }
    44. Long articleId = Long.parseLong((String) map.get("articleId"));
    45. Integer operation = (Integer) map.get("operation");
    46. ApArticle apArticle = getById(articleId);
    47. UpdateArticleMess mess = new UpdateArticleMess();
    48. mess.setArticleId(articleId);
    49. mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
    50. if(apArticle != null) {
    51. //获取文章点赞数
    52. Integer likes = apArticle.getLikes();
    53. if(likes == null) {
    54. likes = 0;
    55. }
    56. //更新文章点赞数
    57. LambdaUpdateWrapper luw = new LambdaUpdateWrapper<>();
    58. luw.eq(ApArticle::getId,articleId);
    59. if(operation == 0) {
    60. //点赞
    61. log.info("用户点赞文章...");
    62. luw.set(ApArticle::getLikes,likes + 1);
    63. //分值增加
    64. mess.setAdd(1);
    65. } else {
    66. //取消点赞
    67. log.info("用户取消点赞文章...");
    68. luw.set(ApArticle::getLikes,likes - 1);
    69. //分值减少
    70. mess.setAdd(-1);
    71. }
    72. //调用Kafka发送消息
    73. kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
    74. update(luw);
    75. }
    76. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    77. }
    78. /**
    79. * 用户收藏
    80. * @param map
    81. * @return
    82. */
    83. @Override
    84. public ResponseResult collBehavior(Map map) {
    85. if(map == null || map.get("entryId") == null) {
    86. return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    87. }
    88. Long articleId = Long.parseLong((String) map.get("entryId"));
    89. Integer operation = (Integer) map.get("operation");
    90. ApArticle apArticle = getById(articleId);
    91. //消息载体
    92. UpdateArticleMess mess = new UpdateArticleMess();
    93. mess.setArticleId(articleId);
    94. mess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);
    95. if(apArticle != null) {
    96. //获取文章收藏数
    97. Integer collection = apArticle.getCollection();
    98. if(collection == null) {
    99. collection = 0;
    100. }
    101. //更新文章收藏数
    102. LambdaUpdateWrapper luw = new LambdaUpdateWrapper<>();
    103. luw.eq(ApArticle::getId,articleId);
    104. if(operation == 0) {
    105. //收藏
    106. log.info("用户收藏文章...");
    107. luw.set(ApArticle::getCollection,collection + 1);
    108. mess.setAdd(1);
    109. } else {
    110. //取消收藏
    111. log.info("用户取消收藏文章...");
    112. luw.set(ApArticle::getCollection,collection - 1);
    113. mess.setAdd(-1);
    114. }
    115. //调用Kafka发送消息
    116. kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
    117. update(luw);
    118. }
    119. return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    120. }

            这一步主要是当用户对文章进行访问、点赞、评论或者收藏时候就会更新数据库中的记录,同时还要将该行为记录封装并发送至Kafka。

    2.3:定义Stream实现消息接收并聚合

    1. package com.my.article.stream;
    2. import com.alibaba.fastjson.JSON;
    3. import com.my.common.constans.HotArticleConstants;
    4. import com.my.model.mess.ArticleVisitStreamMess;
    5. import com.my.model.mess.UpdateArticleMess;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.apache.commons.lang3.StringUtils;
    8. import org.apache.kafka.streams.KeyValue;
    9. import org.apache.kafka.streams.StreamsBuilder;
    10. import org.apache.kafka.streams.kstream.*;
    11. import org.springframework.context.annotation.Bean;
    12. import org.springframework.context.annotation.Configuration;
    13. import java.time.Duration;
    14. @Configuration
    15. @Slf4j
    16. public class HotArticleStreamHandler {
    17. @Bean
    18. public KStream kStream(StreamsBuilder streamsBuilder){
    19. //接收消息
    20. KStream stream = streamsBuilder.stream(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC);
    21. //聚合流式处理
    22. stream.map((key,value)->{
    23. UpdateArticleMess mess = JSON.parseObject(value, UpdateArticleMess.class);
    24. //重置消息的key:1234343434 和 value: likes:1
    25. return new KeyValue<>(mess.getArticleId().toString(),mess.getType().name()+":"+mess.getAdd());
    26. })
    27. //按照文章id进行聚合
    28. .groupBy((key,value)->key)
    29. //时间窗口 每十秒聚合一次
    30. .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
    31. /*
    32. 自行地完成聚合的计算
    33. */
    34. .aggregate(new Initializer() {
    35. /**
    36. * 初始方法,返回值是消息的value
    37. */
    38. @Override
    39. public String apply() {
    40. return "COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0";
    41. }
    42. /*
    43. 真正的聚合操作,返回值是消息的value
    44. */
    45. }, new Aggregator() {
    46. /**
    47. * 聚合并返回
    48. * @param key 文章id
    49. * @param value 重置后的value ps:likes:1
    50. * @param aggValue "COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0"
    51. * @return aggValue格式
    52. */
    53. @Override
    54. public String apply(String key, String value, String aggValue) {
    55. //用户没有进行任何操作
    56. if(StringUtils.isBlank(value)){
    57. return aggValue;
    58. }
    59. String[] aggAry = aggValue.split(",");
    60. //收藏、评论、点赞、阅读量初始值
    61. int col = 0,com=0,lik=0,vie=0;
    62. for (String agg : aggAry) {
    63. //for --> COLLECTION:0
    64. String[] split = agg.split(":");
    65. //split[0]:COLLECTION,split[1]:0
    66. /*
    67. 获得初始值,也是时间窗口内计算之后的值
    68. 第一次获取到的值为0
    69. */
    70. switch (UpdateArticleMess.UpdateArticleType.valueOf(split[0])){
    71. case COLLECTION:
    72. col = Integer.parseInt(split[1]);
    73. break;
    74. case COMMENT:
    75. com = Integer.parseInt(split[1]);
    76. break;
    77. case LIKES:
    78. lik = Integer.parseInt(split[1]);
    79. break;
    80. case VIEWS:
    81. vie = Integer.parseInt(split[1]);
    82. break;
    83. }
    84. }
    85. /*
    86. 累加操作
    87. */
    88. String[] valAry = value.split(":");
    89. switch (UpdateArticleMess.UpdateArticleType.valueOf(valAry[0])){
    90. case COLLECTION:
    91. col += Integer.parseInt(valAry[1]);
    92. break;
    93. case COMMENT:
    94. com += Integer.parseInt(valAry[1]);
    95. break;
    96. case LIKES:
    97. lik += Integer.parseInt(valAry[1]);
    98. break;
    99. case VIEWS:
    100. vie += Integer.parseInt(valAry[1]);
    101. break;
    102. }
    103. String formatStr = String.format("COLLECTION:%d,COMMENT:%d,LIKES:%d,VIEWS:%d", col, com, lik, vie);
    104. log.info("文章的id:{}",key);
    105. log.info("当前时间窗口内的消息处理结果:{}",formatStr);
    106. //必须返回和apply()的返回类型
    107. return formatStr;
    108. }
    109. }, Materialized.as("hot-article-stream-count-001"))
    110. .toStream()
    111. .map((key,value)->{
    112. return new KeyValue<>(key.key().toString(),formatObj(key.key().toString(),value));
    113. })
    114. //发送消息
    115. .to(HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC);
    116. return stream;
    117. }
    118. /**
    119. * 格式化消息的value数据
    120. * @param articleId 文章id
    121. * @param value 聚合结果
    122. * @return String
    123. */
    124. public String formatObj(String articleId,String value){
    125. ArticleVisitStreamMess mess = new ArticleVisitStreamMess();
    126. mess.setArticleId(Long.valueOf(articleId));
    127. //COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0
    128. String[] valAry = value.split(",");
    129. for (String val : valAry) {
    130. String[] split = val.split(":");
    131. switch (UpdateArticleMess.UpdateArticleType.valueOf(split[0])){
    132. case COLLECTION:
    133. mess.setCollect(Integer.parseInt(split[1]));
    134. break;
    135. case COMMENT:
    136. mess.setComment(Integer.parseInt(split[1]));
    137. break;
    138. case LIKES:
    139. mess.setLike(Integer.parseInt(split[1]));
    140. break;
    141. case VIEWS:
    142. mess.setView(Integer.parseInt(split[1]));
    143. break;
    144. }
    145. }
    146. log.info("聚合消息处理之后的结果为:{}",JSON.toJSONString(mess));
    147. return JSON.toJSONString(mess);
    148. }
    149. }

            这一步是最难但是也是最重要的,首先我们接收到消息之后需要先对其key和value进行重置,因为这时候接收到的数据是一个JSON字符串格式的UpdateArticleMess对象,我们需要将其重置为key value键值对的格式。也即将其格式转化成key为文章id,value为用户行为记录,如key:182738789987,value:LIKES:1,表示用户对该文章点赞一次。随后选择对文章id进行聚合,每10秒钟聚合一次,需要注意的是,apply()函数中返回结构必须是“COLLECTION:0,COMMENT:0,LIKES:0,VIEWS:0”格式。

    2.4:重新计算文章分值并更新Redis缓存数据

    1. @Service
    2. @Transactional
    3. @Slf4j
    4. public class ApArticleServiceImpl extends ServiceImpl implements ApArticleService {
    5. /**
    6. * 更新文章分值,同时更新redis中热点文章数据
    7. * @param mess
    8. */
    9. @Override
    10. public void updateScore(ArticleVisitStreamMess mess) {
    11. //1.获取文章数据
    12. ApArticle apArticle = getById(mess.getArticleId());
    13. //2.计算文章分值
    14. Integer score = computeScore(apArticle);
    15. score = score * 3;
    16. //3.替换当前文章对应频道热点数据
    17. replaceDataToRedis(apArticle,score,ArticleConstas.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
    18. //4.替换推荐频道文章热点数据
    19. replaceDataToRedis(apArticle,score,ArticleConstas.HOT_ARTICLE_FIRST_PAGE + ArticleConstas.DEFAULT_TAG);
    20. }
    21. /**
    22. * 根据权重计算文章分值
    23. * @param apArticle
    24. * @return
    25. */
    26. private Integer computeScore(ApArticle apArticle) {
    27. Integer score = 0;
    28. if(apArticle.getLikes() != null){
    29. score += apArticle.getLikes() * ArticleConstas.HOT_ARTICLE_LIKE_WEIGHT;
    30. }
    31. if(apArticle.getViews() != null){
    32. score += apArticle.getViews();
    33. }
    34. if(apArticle.getComment() != null){
    35. score += apArticle.getComment() * ArticleConstas.HOT_ARTICLE_COMMENT_WEIGHT;
    36. }
    37. if(apArticle.getCollection() != null){
    38. score += apArticle.getCollection() * ArticleConstas.HOT_ARTICLE_COLLECTION_WEIGHT;
    39. }
    40. return score;
    41. }
    42. /**
    43. * 替换数据并存入到redis
    44. * @param apArticle 文章信息
    45. * @param score 文章新的得分
    46. * @param key redis数据的key值
    47. */
    48. private void replaceDataToRedis(ApArticle apArticle,Integer score, String key) {
    49. String articleListStr = cacheService.get(key);
    50. if(StringUtils.isNotBlank(articleListStr)) {
    51. List hotArticleVos = JSON.parseArray(articleListStr, HotArticleVo.class);
    52. boolean flag = true;
    53. //如果缓存中存在该文章,直接更新文章分值
    54. for (HotArticleVo hotArticleVo : hotArticleVos) {
    55. if(hotArticleVo.getId().equals(apArticle.getId())) {
    56. if(key.equals(ArticleConstas.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId())) {
    57. log.info("频道{}缓存中存在该文章,文章{}分值更新{}-->{}",apArticle.getChannelName(),apArticle.getId(),hotArticleVo.getScore(),score);
    58. } else {
    59. log.info("推荐频道缓存中存在该文章,文章{}分值更新{}-->{}",apArticle.getId(),hotArticleVo.getScore(),score);
    60. }
    61. hotArticleVo.setScore(score);
    62. flag = false;
    63. break;
    64. }
    65. }
    66. //如果缓存中不存在该文章
    67. if(flag) {
    68. //缓存中热点文章数少于30,直接增加
    69. if(hotArticleVos.size() < 30) {
    70. log.info("该文章{}不在缓存,但是文章数少于30,直接添加",apArticle.getId());
    71. HotArticleVo hotArticleVo = new HotArticleVo();
    72. BeanUtils.copyProperties(apArticle,hotArticleVo);
    73. hotArticleVo.setScore(score);
    74. hotArticleVos.add(hotArticleVo);
    75. } else {
    76. //缓存中热点文章数大于或等于30
    77. //1.排序
    78. hotArticleVos = hotArticleVos.stream().sorted(Comparator.
    79. comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
    80. //2.获取最小得分值
    81. HotArticleVo minScoreHotArticleVo = hotArticleVos.get(hotArticleVos.size() - 1);
    82. if(minScoreHotArticleVo.getScore() <= score) {
    83. //3.移除分值最小文章
    84. log.info("替换分值最小的文章...");
    85. hotArticleVos.remove(minScoreHotArticleVo);
    86. HotArticleVo hotArticleVo = new HotArticleVo();
    87. BeanUtils.copyProperties(apArticle,hotArticleVo);
    88. hotArticleVo.setScore(score);
    89. hotArticleVos.add(hotArticleVo);
    90. }
    91. }
    92. }
    93. //重新排序并缓存到redis
    94. hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
    95. .collect(Collectors.toList());
    96. cacheService.set(key,JSON.toJSONString(hotArticleVos));
    97. if(key.equals(ArticleConstas.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId())) {
    98. log.info("成功刷新{}频道中热点文章缓存数据",apArticle.getChannelName());
    99. } else {
    100. log.info("成功刷新推荐频道中热点文章缓存数据");
    101. }
    102. }
    103. }
    104. }

            这一步主要是逻辑处理部分,在这里我们需要完成对文章的得分进行重新计算并根据计算结果更新Redis中的缓存数据。计算到得分之后,我们需要分别对不同频道和推荐频道进行处理,但是处理流程相同。首先我们会先判断缓存中的数据有没有满30条,如果没满则直接该文章添加到缓存中作为热榜文章;如果缓存中已满30条数据,这时候就要分两种情况处理,如果缓存中存在该文章数据,则直接对其得分进行更新,如若不然则需要将该文章分值与缓存中的最低分进行比较,如果改文章得分比最低分高则直接进行替换,否则不做处理。最后还需要对缓存中的数据重新排序并再次发送到Reids中。

    2.5:设置监听类

    1. package com.my.article.listener;
    2. import com.alibaba.fastjson.JSON;
    3. import com.my.article.service.ApArticleService;
    4. import com.my.common.constans.HotArticleConstants;
    5. import com.my.model.mess.ArticleVisitStreamMess;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.apache.commons.lang3.StringUtils;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.kafka.annotation.KafkaListener;
    10. import org.springframework.stereotype.Component;
    11. @Component
    12. @Slf4j
    13. public class ArticleIncrHandleListener {
    14. @Autowired
    15. private ApArticleService apArticleService;
    16. @KafkaListener(topics = HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC)
    17. public void onMessage(String mess){
    18. if(StringUtils.isNotBlank(mess)){
    19. ArticleVisitStreamMess articleVisitStreamMess = JSON.parseObject(mess, ArticleVisitStreamMess.class);
    20. apArticleService.updateScore(articleVisitStreamMess);
    21. }
    22. }
    23. }

    三:功能测试

    打开App端对一篇文章进行浏览并点赞收藏

    到控制台查看日志信息 

            可以看到 成功记录用户行为并且将文章得分进行了更改,其处理流程是这样的,首先接收到的是用户的点赞数据,随后接收到用户的浏览记录,最后接收到的是用户的收藏记录,由于前面提到的消息处理是增加而不是更新,所以最后我们可以看到时间窗口处理结果为COLLECTION:1,COMMENT:0,LIKES:1,VIEWS:1,10秒钟之后就会对消息进行聚合,假如这10秒之内还有其他用户也进行了点赞阅读操作,这时候就会继续将消息增加在原来处理结果上面,过了10秒之后就会进行一次聚合处理,也即拿着这批数据进行数据更新操作。

    至此该项目的开发就告一段落了,后续有什么优化我会再发文介绍。

    友情链接: 牛客网  刷题|面试|找工作神器

  • 相关阅读:
    MacOS 控制固态磁盘写入量,设置定时任务监控
    价格监测的目标
    shiro组件漏洞分析(二)
    【Java面试八股文宝典之基础篇】备战2023 查缺补漏 你越早准备 越早成功!!!——Day08
    一键部署(dhcp、dns、pxe、raid、nfs+apache+expect、lvm、磁盘分区、监控资源)
    根目录/ 空间不够,扩容,导致web页面无法加载问题
    常识判断 --- 科技常识
    CF比赛1610D. Not Quite Lee(Codeforces Global Round 17)(数学)(计数)
    SRT参数说明
    latex cite命令、款式
  • 原文地址:https://blog.csdn.net/weixin_45750572/article/details/126100115