RabbitMQ组件封装

1.组件需求

需求:需要单独设计一个模块用来封装rabbitmq 其他应用之间引用,做简单少量的配置,即可发送消息,消息的发送要保证可靠的投递

2.组件架构选型

消息组件:rabbitMQ
消息可靠性保证:使用elasticjob查询数据库相关表记录来对消息进行可靠投递

3.模块分类RabbitMQ组件封装_第1张图片

相关依赖



    4.0.0
    
        rabbit-common
        rabbit-api
        rabbit-core-producer
        rabbit-task
        rabbit-test
    
    
        spring-boot-starter-parent
        org.springframework.boot
        2.1.5.RELEASE
        
    
    cn.xp.rabbitmq.parent
    rabbitmq-parent
    1.0-SNAPSHOT
    rabbit-parent
    pom
    
        UTF-8
        8
        8
        8
        3.1.4
        1.9.13
        1.0.24
        2.1.4
        20.0
        1.2.2
        3.3.1
        2.4
        3.2.2
        2.11.0
        1.1.26
    

    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
            provided
        
        
            com.google.guava
            guava
            ${guava.version}
        
        
            commons-fileupload
            commons-fileupload
            ${commons-fileupload.version}
        
        
            org.apache.commons
            commons-lang3
        
        
            commons-io
            commons-io
            ${commons-io.version}
        
        
            com.alibaba
            fastjson
            ${fastjson.version}
        
        
            com.fasterxml.jackson.core
            jackson-databind
        
        
            org.codehaus.jackson
            jackson-mapper-asl
            ${org.codehaus.jackson.version}
        
        
            com.fasterxml.uuid
            java-uuid-generator
            ${fasterxml.uuid.version}
        
    




1.rabbit- api

RabbitMQ组件封装_第2张图片
1.message消息传输类

package com.xp.rabbitmq.api;

import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author xp
 * @Description 消息类
 **/
@Data
public class Message implements Serializable {
    /* 消息的ID*/
    private String messageId;

    /* 消息的主题/消息的交换机 */
    private String messageTopic="";

    /*消息的路由规则*/
    private String messageRouteKey="";


    /*消息的属性*/
    private Map messageAttribute=new HashMap<>();

    /*消息类型:默认是确认模式*/
    private String messageType=MessageType.CONFIRM;

    /*消息延迟时间*/
    private Long messageDelay;

    public Message() {
    }

    public Message(String messageId, String messageTopic, String messageRouteKey, Map messageAttribute, String messageType, Long messageDelay) {
        this.messageId = messageId;
        this.messageTopic = messageTopic;
        this.messageRouteKey = messageRouteKey;
        this.messageAttribute = messageAttribute;
        this.messageType = messageType;
        this.messageDelay = messageDelay;
    }

    public Message(String messageId, String messageTopic, String messageRouteKey, Map messageAttribute, Long messageDelay) {
        this.messageId = messageId;
        this.messageTopic = messageTopic;
        this.messageRouteKey = messageRouteKey;
        this.messageAttribute = messageAttribute;
        this.messageDelay = messageDelay;
    }
}

2.使用建造者模式构造message—MessageBuilder

package com.xp.rabbitmq.api;

import com.xp.rabbitmq.exception.MessageRuntimeException;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author xp
 * @Description 建造者模式:链式创建对象
 **/
public class MessageBuilder {
    /* 消息的ID*/
    private String messageId;
    /* 消息的主题 */
    private String messageTopic;
    /*消息的路由规则*/
    private String messageRouteKey="";
    /*消息的属性*/
    private Map messageAttribute=new HashMap<>();
    /*消息类型:默认是确认模式*/
    private String messageType=MessageType.CONFIRM;
    /*消息延迟时间*/
    private Long messageDelay;

    public MessageBuilder() {
    }

    public static MessageBuilder builder(){
        return new MessageBuilder();
    }

    public MessageBuilder withMessageId(String messageId){
        this.messageId=messageId;
        return this;
    }

    public MessageBuilder withMessageTopic(String messageTopic){
        this.messageTopic=messageTopic;
        return this;
    }

    public MessageBuilder withMessageRouteKey(String messageRouteKey){
        this.messageRouteKey=messageRouteKey;
        return this;
    }

    public MessageBuilder withMessageAttributes(Map messageAttribute){
        this.messageAttribute=messageAttribute;
        return this;
    }
    public MessageBuilder withMessageAttribute(String key,Object properties){
        this.messageAttribute.put(key,properties);
        return this;
    }
    public MessageBuilder withMessageType(String messageType){
        this.messageType=messageType;
        return this;
    }
    public MessageBuilder withMessageDelay(Long messageDelay){
        this.messageDelay=messageDelay;
        return this;
    }
    public Message build(){
        if(StringUtils.isEmpty(this.messageId)){
            this.messageId= UUID.randomUUID().toString();
        }
        if(StringUtils.isEmpty((this.messageTopic))){
            throw new MessageRuntimeException("消息主题不能为空");
        }

        Message message=new Message(messageId,messageTopic,messageRouteKey,messageAttribute,messageType,messageDelay);

        return message;
    }


}

3.消息发送类MessageProducer

package com.xp.rabbitmq.api;

import com.xp.rabbitmq.exception.MessageRuntimeException;

import java.util.List;

/*
消息发送接口
 */
public interface MessageProducer {

    void send(Message message) throws MessageRuntimeException;
    void send(Message message,SendCallback sendCallback) throws MessageRuntimeException;
    void send(List messageList) throws MessageRuntimeException;
    void send(List messageList,SendCallback sendCallbackList) throws MessageRuntimeException;


}

4.消息分类MessageType

package com.xp.rabbitmq.api;

/**
 * @Author xp
 * @Description 消息类型
 **/
public class MessageType {
    /* 快速消息:不用确认,不用必须可靠 */
    public static final String RAPID="0";

    /* 确认消息:需要回调确认*/
    public static final String CONFIRM="1";


    /* 可靠消息:必须保证消息发送*/
    public static final String RELIABLE="2";

}

5.相关异常处理

package com.xp.rabbitmq.exception;

/**
 * @Author xp
 * @Description 消息未严格封装异常类
 **/
public class MessageException extends Exception{

    public MessageException() {
        super();
    }
    public MessageException(String exception) {
        super(exception);
    }
    public MessageException(String exception,Throwable throwable) {
        super(exception,throwable);
    }
    public MessageException(Throwable throwable) {
        super(throwable);
    }




}
package com.xp.rabbitmq.exception;

/**
 * @Author xp
 * @Description 运行时异常
 **/
public class MessageRuntimeException extends RuntimeException{
    public MessageRuntimeException() {
        super();
    }
    public MessageRuntimeException(String exception) {
        super(exception);
    }
    public MessageRuntimeException(String exception,Throwable throwable) {
        super(exception,throwable);
    }
    public MessageRuntimeException(Throwable throwable) {
        super(throwable);
    }
}

2.rabbit-common

RabbitMQ组件封装_第3张图片
包含消息进行序列化 反序列化处理
1.序列化接口Serializer

package com.xp.rabbit.common.serializer;

public interface Serializer {
    //对象序列化为byte数组
    byte[] serializerRaw(Object object);
    //对象序列化string
    String serializer(Object object);
    //string反序列化对象
    T deserializer(String content);
    //数组反序列化对象
    T deserializer( byte[] content);
}

2.相关实现 SerializerImpl

package com.xp.rabbit.common.impl;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.xp.rabbit.common.serializer.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * @Author xp
 * @Description
 **/
public class SerializerImpl implements Serializer {
    private static final Logger LOGGER= LoggerFactory.getLogger(SerializerImpl.class);
    private static final ObjectMapper mapper=new ObjectMapper();
    static {
        mapper.disable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS,true);
        mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER,true);
        mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS,true);
        mapper.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS,true);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
    }

    private final JavaType type;

    public SerializerImpl(JavaType type) {
        this.type = type;
    }

    public static SerializerImpl createParametricType(Class cls){
        return new SerializerImpl(mapper.getTypeFactory().constructType(cls));
    }

    @Override
    public byte[] serializerRaw(Object object) {
        try{
            return mapper.writeValueAsBytes(object);
        }catch (JsonProcessingException e){
            LOGGER.error("序列化出错",e);
        }
        return null;
    }

    @Override
    public String serializer(Object object) {
        try{
            return mapper.writeValueAsString(object);
        }catch (JsonProcessingException e){
            LOGGER.error("序列化出错",e);
        }
        return null;
    }

    @Override
    public  T deserializer(String content) {
        try{
            return mapper.readValue(content,type);
        }catch (IOException e){
            LOGGER.error("反序列化出错",e);
        }
        return null;
    }

    @Override
    public  T deserializer(byte[] content) {
        try{
            return mapper.readValue(content,type);
        }catch (IOException e){
            LOGGER.error("反序列化出错",e);
        }
        return null;
    }
}

3.单例工厂模式产生序列化对象

package com.xp.rabbit.common.serializer;

/**
 * @Author xp
 * @Description
 **/
public interface SerializerFactory {

    Serializer create();
}


package com.xp.rabbit.common.impl;

import com.xp.rabbit.common.serializer.Serializer;
import com.xp.rabbit.common.serializer.SerializerFactory;
import com.xp.rabbitmq.api.Message;

/**
 * @Author xp
 * @Description
 **/
public class SerializerFactoryImpl implements SerializerFactory {
    public static final SerializerFactoryImpl INSTANCE=new SerializerFactoryImpl();
    @Override
    public Serializer create() {
        return SerializerImpl.createParametricType(Message.class);
    }
}

4.对象转json类

package com.xp.rabbit.common.util;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 	$FastJsonConvertUtil java对象与json进行转换的通用工具类
 * 
 *
 */
public class FastJsonConvertUtil {

	private static final SerializerFeature[] featuresWithNullValue = { SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse,
	        SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsE

你可能感兴趣的:(rabbitmq,java,rabbitmq,分布式,java,elastic-job,zookeeper)