转:https://blog.csdn.net/qq_42175986/article/details/88576849

pom.xml

<!-- redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- redis依赖 -->

application.yml

spring:
application:
name: yys-redismq
redis:
host: 127.0.0.1
port:
password:
pool:
max-active:
max-idle:
min-idle:
max-wait:
timeout:
database: server:
port:
tomcat:
uri-encoding: UTF-

RedisConfig.java

package com.yys.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig; /**
* 描述:redis配置类
* @author yys
* @date 2019.03.15
*/
@Configuration
public class RedisConfig { /** redis 服务器地址 */
@Value("${spring.redis.host}")
private String host; /** redis 端口号 */
@Value("${spring.redis.port}")
private int port; /** redis 服务器密码 */
@Value("${spring.redis.password}")
private String password; /** redis 连接池最大连接数(使用负值无限制) */
@Value("${spring.redis.pool.max-active}")
private int maxActive; /** redis 连接池最大空闲数 */
@Value("${spring.redis.pool.max-idle}")
private int maxIdle; /** redis 连接池小空闲数 */
@Value("${spring.redis.pool.min-idle}")
private int minIdle; /** redis 连接池最大阻塞等待时间(负值无限制) */
@Value("${spring.redis.pool.max-wait}")
private int maxWait; /** redis 数据库索引(默认0) */
@Value("${spring.redis.database}")
private int database; /** redis 超时时间 */
@Value("${spring.redis.timeout}")
private int timeout; @Bean
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setMaxWaitMillis(maxWait);
return config;
} @Bean
public JedisConnectionFactory getConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setDatabase(database);
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
return factory;
} @Bean
public RedisTemplate<?, ?> getRedisTemplate() {
JedisConnectionFactory factory = getConnectionFactory();
RedisTemplate<?, ?> redisTemplate = new StringRedisTemplate(factory);
return redisTemplate;
} }

RedisClient.java

package com.yys.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; /**
* 描述:redis工具类(本配置类只有redis消息队列相关命令方法)
* @author yys
* @date 2019.03.15
*/
@Component
public class RedisClient { @Autowired
private RedisTemplate<String, Object> redisTemplate; /** ---------------------------------- redis消息队列 ---------------------------------- */
/**
* 存值
* @param key 键
* @param value 值
* @return
*/
public boolean lpush(String key, Object value) {
try {
redisTemplate.opsForList().leftPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 取值 - <rpop:非阻塞式>
* @param key 键
* @return
*/
public Object rpop(String key) {
try {
return redisTemplate.opsForList().rightPop(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 取值 - <brpop:阻塞式> - 推荐使用
* @param key 键
* @param timeout 超时时间
* @param timeUnit 给定单元粒度的时间段
* TimeUnit.DAYS //天
* TimeUnit.HOURS //小时
* TimeUnit.MINUTES //分钟
* TimeUnit.SECONDS //秒
* TimeUnit.MILLISECONDS //毫秒
* @return
*/
public Object brpop(String key, long timeout, TimeUnit timeUnit) {
try {
return redisTemplate.opsForList().rightPop(key, timeout, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* 查看值
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lrange(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /** ---------------------------------- redis消息队列 ---------------------------------- */ }

RedisProducerController.java

package com.yys.demo.controller;

import com.yys.demo.config.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Arrays;
import java.util.List; /**
* 描述:生产者(消息发送方)
* @author yys
* @date 2019.03.15
*/
@RestController
@RequestMapping("/producer")
public class RedisProducerController { @Autowired
RedisClient redisClient; /** 公共配置 */
private final static String SUCCESS = "success";
private final static String MESSAGE = "testmq";
private static final List<String> list; static {
list = Arrays.asList(new String[]{"猿医生", "CD", "yys"});
} /**
* 消息发送API
* @return
*/
@RequestMapping("/sendMessage")
public String sendMessage() {
for (String message : list) {
redisClient.lpush(MESSAGE, message);
}
return SUCCESS;
} }

RedisConsumerController.java

package com.yys.demo.controller;

import com.yys.demo.config.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.TimeUnit; /**
* 描述:消费者(消息接收方)
* @author yys
* @date 2019.03.15
*/
@RestController
@RequestMapping("/consumer")
public class RedisConsumerController { @Autowired
RedisClient redisClient; /** 公共配置 */
private final static String MESSAGE = "testmq"; /**
* 接收消息API
* @return
*/
@RequestMapping("/receiveMessage")
public String sendMessage() {
return (String) redisClient.brpop(MESSAGE, 0, TimeUnit.SECONDS);
} }

注:批量消费消息例子如下

package com.cashloan.analytics.controller;

import com.cashloan.analytics.model.DcProjectCount;
import com.cashloan.analytics.utils.RedisQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit; @RestController
@RequestMapping("/test")
public class Test {
@Autowired
private RedisQueue redisQueue; /** 公共配置 */
private final static String MESSAGE = "testmq"; @RequestMapping("/send")
public String sendMessage(String[] strs) {
List<String> str = Arrays.asList(strs);
for (String msg : str) {
DcProjectCount dcProjectCount = new DcProjectCount();
dcProjectCount.setId(Long.valueOf(msg));
redisQueue.lpush(MESSAGE, dcProjectCount);
}
return "1";
} @GetMapping("/see")
public List<Object> see() {
List<Object> lrange = redisQueue.lrange(MESSAGE, 0, -1);
return lrange;
} @GetMapping("/get")
public Object get() {
List<Object> lrange = redisQueue.lrange(MESSAGE, 0, -1);
int size = lrange.size();
System.out.println("size:" + size);
if (size >= 10) {
List<DcProjectCount> dcProjectCounts = new ArrayList<>();
for (int i = 0; i < size; i++) {
Object brpop = redisQueue.brpop(MESSAGE, 0, TimeUnit.SECONDS);
if (brpop != null) {
dcProjectCounts.add((DcProjectCount) brpop);
}
}
for (DcProjectCount dcProjectCount : dcProjectCounts) {
System.out.println(dcProjectCount.getId());
}
}
return "true";
}
}

DcProjectCount类只要设置private Long id并添加set、get方法即可!

redis实现消息队列-java代码实现的更多相关文章

  1. Redis 做消息队列

    一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式.利用redis这两种场景的消息队列都能够实现.定义: 生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列, ...

  2. Redis除了做缓存--Redis做消息队列/Redis做分布式锁/Redis做接口限流

    1.用Redis实现消息队列 用命令lpush入队,rpop出队 Long size = jedis.lpush("QueueName", message);//返回存放的数据条数 ...

  3. Redis作为消息队列服务场景应用案例

    NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例   一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更 ...

  4. Lumen开发:结合Redis实现消息队列(1)

    1.简介 Lumen队列服务为各种不同的后台队列提供了统一的API.队列允许你推迟耗时任务(例如发送邮件)的执行,从而大幅提高web请求速度. 1.1 配置 .env文件的QUEUE_DRIVER选项 ...

  5. 程序员过关斩将--redis做消息队列,香吗?

    Redis消息队列 在程序员这个圈子打拼了太多年,见过太多的程序员使用redis,其中一部分喜欢把redis做缓存(cache)使用,其中最典型的当属存储用户session,除此之外,把redis作为 ...

  6. redis resque消息队列

    Resque 目前正在学习使用resque .resque-scheduler来发布异步任务和定时任务,为了方便以后查阅,所以记录一下. resque和resque-scheduler其优点在于功能比 ...

  7. 【springboot】【redis】springboot+redis实现发布订阅功能,实现redis的消息队列的功能

    springboot+redis实现发布订阅功能,实现redis的消息队列的功能 参考:https://www.cnblogs.com/cx987514451/p/9529611.html 思考一个问 ...

  8. 【Redis】php+redis实现消息队列

    在项目中使用消息队列一般是有如下几个原因: 把瞬间服务器的请求处理换成异步处理,缓解服务器的压力 实现数据顺序排列获取 redis实现消息队列步骤如下: 1).redis函数rpush,lpop 2) ...

  9. sping+redis实现消息队列的乱码问题

    使用spring支持redis实现消息队列,参考官方样例:https://spring.io/guides/gs/messaging-redis/ 实现后在运行过程中发现消费者在接收消息时会出现乱码的 ...

随机推荐

  1. 深入js系列-类型(开篇)

    思考 作为一个编程人员,你可能从来没仔细思考过,为什么这么多高级语言会有类型这东西. 实际上,类型有点类似生活中的类别,我们日常生活,早已经把这个概念理解到了,切肉和切水果会用不同的刀. 语言级别的类 ...

  2. BootStrap Table 合并单元格

    为了更直观展示表格的一大堆乱七八糟的数据,合并单元格就派上用场: 效果: 贴上JSON数据(后台查询数据一定要对合并字段排序): [ { "city": "广州市&quo ...

  3. LDoc使用总结

    LDoc使用总结 安装 按照下面的安装就可以了 http://www.cnblogs.com/ZhYQ-Note/articles/6022525.html 使用 参考:官方的说明文档 https:/ ...

  4. asp.net core api 跨域配置

    项目前后端分离,前端请求接口例如使用axios发送请求时浏览器会提示跨域错误,需要后端配置允许接口跨域 配置步骤: 1.通过NuGet安装Microsoft.AspNetCore.Cors.dll类库 ...

  5. odoo13 searchpanel tree

    <record id="view_department_filter" model="ir.ui.view"> <field name=&qu ...

  6. Linux内核device结构体分析

    1.前言 Linux内核中的设备驱动模型,是建立在sysfs设备文件系统和kobject上的,由总线(bus).设备(device).驱动(driver)和类(class)所组成的关系结构,在底层,L ...

  7. 第十四节:Asp.Net Core 中的跨域解决方案(Cors、jsonp改造、chrome配置)

    一. 整体说明 1. 说在前面的话 早在前面的章节中,就详细介绍了.Net FrameWork版本下MVC和WebApi的跨域解决方案,详见:https://www.cnblogs.com/yaope ...

  8. ZYNQ笔记(7):AXI从口自定义IP封装

    使用 AXI_Lite 从口实现寄存器列表的读写,并且自己封装为一个自定义 IP,以便以后使用.本次记录的是 M_AXI_GP0 接口,此接口是 ARM 作为主机,FPGA 作为从机,配置 FPGA ...

  9. 算法设计与分析(李春保)练习题答案v1

    1.1第1 章─概论 1.1.1练习题 1.下列关于算法的说法中正确的有(). Ⅰ.求解某一类问题的算法是唯一的 Ⅱ.算法必须在有限步操作之后停止 Ⅲ.算法的每一步操作必须是明确的,不能有歧义或含义模 ...

  10. Java学习:运算符的使用与注意事项

    运算符的使用与注意事项 四则运算当中的加号“+”有常见的三种用法: 对于数值来,那就是加法. 对于字符char类型来说,在计算之前,char会被提升成为int,然后再计算.char类型字符,和int类 ...