消息队列 - 基于SpringBoot实现多种消息队列

7 篇文章 0 订阅

目录

基于SpringBoot实现多种消息队列

SpringBoot + redis 实现消息队列

说明

pom文件  

连接redis 

redisConfig配置

测试配置是否可用

消息发送与接收

测试


基于SpringBoot实现多种消息队列

SpringBoot 2.2.6

SpringBoot + redis 实现消息队列

  • 说明

基于redis的list结构实现,方法leftPush与rightPop
  • pom文件  

  • spring-data-redis版本要与springboot版本对应

	<dependencies>
		<!-- Spring Boot redis 依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-redis</artifactId>
			<version>1.4.7.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<!--<version>1.7.1.RELEASE</version>-->
			<version>2.2.6.RELEASE</version>
		</dependency>

		<!-- java快速序列化库FST -->
		<dependency>
			<groupId>de.ruedigermoeller</groupId>
			<artifactId>fst</artifactId>
			<version>1.36</version>
		</dependency>
		<dependency>
	    	<groupId>org.springframework.boot</groupId>
	    	<artifactId>spring-boot-configuration-processor</artifactId>
	    	<optional>true</optional>
	    </dependency>
	</dependencies>
  • 连接redis 

  • yml文件 此处redis使用的集群
server:
  port: 80
  context-path: /

spring:
  redis:
    cluster:
      max-redirects: 10
      nodes:
        - 192.168.0.148:7001
        - 192.168.0.148:7006
        - 192.168.0.148:7001
  • redisConfig配置

  • RedisClusterProperties
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;

@ConfigurationProperties(prefix= RedisClusterProperties.REDIS_CLUSTER_PREFIX)
public class RedisClusterProperties {
	public static final String REDIS_CLUSTER_PREFIX = "spring.redis.cluster";
	private List<String> nodes;
	private Integer maxRedirects;
	
	public List<String> getNodes() {
		return nodes;
	}
	
	public void setNodes(List<String> nodes) {
		this.nodes = nodes;
	}
	
	public Integer getMaxRedirects() {
		return maxRedirects;
	}
	
	public void setMaxRedirects(Integer maxRedirects) {
		this.maxRedirects = maxRedirects;
	}
}
  • RedisClusterAutoConfiguration
import java.lang.reflect.Method;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.awb.common.redis.RedisLock;
import com.awb.common.redis.serializer.FSTSerializer;

@Configuration
@ConditionalOnClass({RedisClusterConfiguration.class, RedisConnectionFactory.class})
@EnableConfigurationProperties(RedisClusterProperties.class)
public class RedisClusterAutoConfiguration {
	@Autowired
	private RedisClusterProperties clusterProperties;
	
	@Bean
	@ConditionalOnMissingBean
	public RedisConnectionFactory connectionFactory() {
		RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(clusterProperties.getNodes());
		clusterConfiguration.setMaxRedirects(clusterProperties.getMaxRedirects());
		return new JedisConnectionFactory(clusterConfiguration);
	}
	
	@Bean
	@ConditionalOnMissingBean
	public RedisClusterConnection clusterConnection(RedisConnectionFactory connectionFactory) {
		return connectionFactory.getClusterConnection();
	}
	
	@Bean
	@ConditionalOnMissingBean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		FSTSerializer serializer = new FSTSerializer();
		redisTemplate.setConnectionFactory(connectionFactory);
		redisTemplate.setKeySerializer(redisTemplate.getStringSerializer());
		redisTemplate.setValueSerializer(serializer);
		redisTemplate.setHashKeySerializer(redisTemplate.getStringSerializer());
		redisTemplate.setHashValueSerializer(serializer);
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}
	
	@Bean
	@ConditionalOnMissingBean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override  
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object param : params) {
                    sb.append(param.toString());
                }
                return sb.toString();
            }
        };
    }
	
//	@Bean
//	@ConditionalOnMissingBean
//    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
//        return new RedisCacheManager(redisTemplate);
//    } 
//	找了很久版本springboot2与1写法不一样

	@Bean
	@ConditionalOnMissingBean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
		RedisCacheManager  redisCacheManager  = RedisCacheManager.create(factory);
        return redisCacheManager;
    }
	
	@Bean
	@ConditionalOnMissingBean
	public RedisLock redisLock(RedisTemplate<String, Object> redisTemplate) {
		return new RedisLock(redisTemplate);
	}
}
  • 测试配置是否可用

import com.awb.common.utils.MessageConsumerUtil;
import com.awb.common.utils.MessageProducerUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@SpringBootTest
public class applicationTests {

	@Autowired
	RedisTemplate<String, Object> redisTemplate;

	@Test
	public void test01() {
		System.out.println("1111111");
	}
	
	@Test
	public void testRedis() {
		redisTemplate.opsForValue().set("key", "value1", 100, TimeUnit.SECONDS);

		Object object = redisTemplate.opsForValue().get("key");
		System.out.println(object);
	}

}

运行,存取成功,配置完成

  • 消息发送与接收

MessageProducerUtil
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MessageProducerUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Long sendMeassage(String queueKey, Object message) {
        System.out.println("发送了--" + "queueKey:" + queueKey + "message:" + message);
        return redisTemplate.opsForList().leftPush(queueKey, message);
    }
}
MessageConsumerUtil
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 接收者
 * @author
 * @date
 */
@Service
public class MessageConsumerUtil extends Thread {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private volatile boolean flag = true;

    private String queueKey = "test";

    private Long popTimeout = 200L;

    @Override
    public void run() {
        try {
            Object message;
            while(flag && !Thread.currentThread().isInterrupted()) {
                message = redisTemplate.opsForList().rightPop(queueKey, popTimeout, TimeUnit.SECONDS);
                System.out.println("接收到了:" + message);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

测试

发布与接收者有了,通过接口下(测试不是很规范,具体要看项目中怎么用)

  • RedisMqController
import com.awb.common.utils.MessageProducerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisMqController {

    @Autowired
    private MessageProducerUtil producer;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public void setCustomerOpenid() {
        String queueKey = "test";
        Object message = "发送一条通知";
        producer.sendMeassage(queueKey, message);
    }
}

方便测试写死了,调用接口,启动类初始化一下接收者的方法

	@PostConstruct
	public void init() {
		System.out.println("初始化方法开始PostConstruct");
		consumer.start();
//		System.out.println("初始化方法结束PostConstruct");
	}

通过ides插件RestfulToolkit 快速测试Controller接口

成功接收,可以再做逻辑处理

SpringBoot + XX实现消息队列

待完成

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑶山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值