COLA框架实现发送消息及监听消息的功能

515 阅读3分钟

COLA框架实现发送消息及监听消息的功能

COLA实现类似消息中间件的简单功能,能够实现发送消息,异步处理消息,例如当我们把数据缓存到Redis中时,修改一条数据的同时需要更新缓存Redis中的数据(异步方式),若不想引入庞大的消息中间件,则可以使用COLA来实现该功能。

1、添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wangzhan</groupId>
    <artifactId>cola-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cola-demo</name>
    <description>cola-demo</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.6.13</spring-boot.version>

        <cola.version>3.0.0</cola.version>
    </properties>

    <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>
            <scope>test</scope>
        </dependency>

        <!--COLA 框架-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>cola-core</artifactId>
            <version>${cola.version}</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>cola-common</artifactId>
            <version>${cola.version}</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.wangzhan.ColaDemoApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2、启动类添加扫描包的路径

image.png

3、定义COLA配置类

package com.wangzhan.cola.config;

import com.alibaba.cola.boot.SpringBootstrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(value = {"com.alibaba.cola"})
public class ColaConfig {

    @Bean(initMethod = "init")
    public SpringBootstrap bootstrap() {
        SpringBootstrap bootstrap = new SpringBootstrap();
        return bootstrap;
    }
}

4、定义通用事件模型

  • 基础通用事件模型(MessageBaseEvent)

    package com.wangzhan.cola.event;
    
    import com.alibaba.cola.event.DomainEventI;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 通用事件模型
     * @date 2024/2/21 17:32:04
     */
    public class MessageBaseEvent implements DomainEventI {
    
        private String message;
    
        public MessageBaseEvent(String message) {
            this.message = message;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        @Override
        public String toString() {
            return "MessageBaseEvent{" +
                    "message='" + message + '\'' +
                    '}';
        }
    }
    
  • 用户消息事件(UserMessageEvent)

    package com.wangzhan.cola.event;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 用户消息事件
     * @date 2024/2/21 17:34:26
     */
    public class UserMessageEvent extends MessageBaseEvent {
    
        private String userName;
    
        public UserMessageEvent(String message) {
            super(message);
        }
    
        public UserMessageEvent(String message, String userName) {
            super(message);
            this.userName = userName;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        @Override
        public String toString() {
            return "UserMessageEvent{" +
                    "userName='" + userName + '\'' +
                    ", msg=" + super.getMessage() +
                    '}';
        }
    }
    
    
  • 活动消息事件(ActivityMessageEvent)

    package com.wangzhan.cola.event;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 活动消息事件
     * @date 2024/2/22 08:24:21
     */
    public class ActivityMessageEvent extends MessageBaseEvent {
    
        private String activityId;
        private String activityName;
    
        public ActivityMessageEvent(String message, String activityId, String activityName) {
            super(message);
            this.activityId = activityId;
            this.activityName = activityName;
        }
    
        @Override
        public String toString() {
            return "ActivityMessageEvent{" +
                    "activityId='" + activityId + '\'' +
                    ", activityName='" + activityName + '\'' +
                    ", msg='" + super.getMessage() + '\'' +
                    '}';
        }
    }
    
    

image.png

5、定义领域事件发布类

  • 发布事件接口(EventPublish)

    package com.wangzhan.cola.publish;
    
    import com.alibaba.cola.event.DomainEventI;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 发布事件接口
     * @date 2024/2/21 17:36:25
     */
    public interface EventPublish {
    
        // 同步发送消息
        void syncPublish(DomainEventI domainEventI);
    
        // 异步发送消息
        void asyncPublish(DomainEventI domainEventI);
    
    }
    
    
  • 发布事件实现类(LocalDomainEventPublish)

    package com.wangzhan.cola.publish.impl;
    
    import com.alibaba.cola.event.DomainEventI;
    import com.alibaba.cola.event.EventBusI;
    import com.wangzhan.cola.publish.EventPublish;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 领域事件发布类
     * @date 2024/2/21 17:37:57
     */
    @Component
    public class LocalDomainEventPublish implements EventPublish {
    
        @Autowired
        private EventBusI eventBusI;
    
        // 同步发送
        @Override
        public void syncPublish(DomainEventI domainEventI) {
            eventBusI.fire(domainEventI);
        }
    
        // 异步发送
        @Override
        public void asyncPublish(DomainEventI domainEventI) {
            eventBusI.asyncFire(domainEventI);
        }
    }
    
    

6、定义领域事件监听类

  • 用户消息监听类(UserMessageListen)

    package com.wangzhan.cola.listen;
    
    import com.alibaba.cola.dto.Response;
    import com.alibaba.cola.event.EventHandler;
    import com.alibaba.cola.event.EventHandlerI;
    import com.wangzhan.cola.event.UserMessageEvent;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 监听领域事件
     * @date 2024/2/21 17:46:07
     */
    @EventHandler
    public class UserMessageListen implements EventHandlerI<Response,UserMessageEvent> {
    
        private static final Logger logger = LoggerFactory.getLogger(UserMessageListen.class);
    
        @Override
        public Response execute(UserMessageEvent userMessageEvent) {
            logger.info("user监听到的消息为:{}", userMessageEvent.toString());
            // TODO 模拟做逻辑处理
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
    
            return Response.buildSuccess();
        }
    }
    
    
  • 活动消息监听类(ActivityMessageListen)

    package com.wangzhan.cola.listen;
    
    import com.alibaba.cola.dto.Response;
    import com.alibaba.cola.event.EventHandler;
    import com.alibaba.cola.event.EventHandlerI;
    import com.wangzhan.cola.event.ActivityMessageEvent;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description 活动消息监听领域事件
     * @date 2024/2/22 08:43:11
     */
    @EventHandler
    public class ActivityMessageListen implements EventHandlerI<Response, ActivityMessageEvent> {
    
        private static final Logger logger = LoggerFactory.getLogger(ActivityMessageListen.class);
    
        @Override
        public Response execute(ActivityMessageEvent activityMessageEvent) {
            logger.info("activity监听到的消息为:{}", activityMessageEvent.toString());
            // TODO 模拟做逻辑处理
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
    
            return Response.buildSuccess();
    
        }
    }
    
    

    7、测试类

    package com.wangzhan.controller;
    
    import com.wangzhan.cola.event.ActivityMessageEvent;
    import com.wangzhan.cola.event.UserMessageEvent;
    import com.wangzhan.cola.publish.EventPublish;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author wangzhan
     * @version 1.0
     * @description
     * @date 2024/2/21 17:23:37
     */
    @RestController
    @RequestMapping(value = "/cola")
    public class ColaController {
    
        private static final Logger logger = LoggerFactory.getLogger(ColaController.class);
    
        @Autowired
        private EventPublish eventPublish;
    
        @RequestMapping(value = "/publishMsg")
        public void publishMsg(@RequestParam("msg") String msg) {
            // 定义领域事件
            UserMessageEvent userMessageEvent = new UserMessageEvent(msg, "wangzhan");
            logger.info("发布的消息为:{}", userMessageEvent.toString());
            eventPublish.syncPublish(userMessageEvent);
        }
    
        // 同步发布批量消息
        @RequestMapping(value = "/syncPublishBatchMsg")
        public void syncPublishBatchMsg(@RequestParam("msg") String msg) throws InterruptedException {
    
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    // 定义领域事件
                    UserMessageEvent userMessageEvent = new UserMessageEvent(i + "-" +msg, "wangzhan-" + i);
                    logger.info(i + "-user发布的消息为:{}", userMessageEvent.toString());
                    eventPublish.syncPublish(userMessageEvent);
                }else {
                    ActivityMessageEvent activityMessageEvent = new ActivityMessageEvent(i + "-" +msg, String.valueOf(i), "小米手机直售-" + i);
                    logger.info(i + "-activity发布的消息为:{}", activityMessageEvent.toString());
                    eventPublish.syncPublish(activityMessageEvent);
                }
            }
    
        }
    
        // 异步发布批量消息
        @RequestMapping(value = "/asyncPublishBatchMsg")
        public void asyncPublishBatchMsg(@RequestParam("msg") String msg) throws InterruptedException {
    
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    // 定义领域事件
                    UserMessageEvent userMessageEvent = new UserMessageEvent(i + "-" +msg, "wangzhan-" + i);
                    logger.info(i + "-user发布的消息为:{}", userMessageEvent.toString());
                    eventPublish.asyncPublish(userMessageEvent);
                }else {
                    ActivityMessageEvent activityMessageEvent = new ActivityMessageEvent(i + "-" +msg, String.valueOf(i), "小米手机直售-" + i);
                    logger.info(i + "-activity发布的消息为:{}", activityMessageEvent.toString());
                    eventPublish.asyncPublish(activityMessageEvent);
                }
            }
    
        }
    }
    
    
  • 发送同步消息及监听

    image-20240222090838066

    发送异步消息及监听

    image-20240222091000149