5分钟学会Redis实现消息队列-java代码实现

                                             Redis实现消息队列-代码实现

一、前言

       再 上一篇 5分钟学会Redis实现消息队列 文章中,重点讲解 redis实现消息队列的 原理实现 

       但作为一个合格的程序猿来say,除了代码一切都是浮云 ... 

       于是,小主在工作闲暇时间,废寝忘食、忘乎所以,还是写了个小demo,供猿友们参考;

           现 代码奉上:

 

二、代码

       项目结构图 :

             

  • 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: 6379
    password: 123456
    pool:
      max-active: 100
      max-idle: 10
      min-idle: 0
      max-wait: 100000
    timeout: 0
    database: 2


server:
    port: 8081
    tomcat:
        uri-encoding: UTF-8

  • 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);
    }

}

三、测试

     

        ①、消费者(消息接收方):发送请求等待接收消息

       ②、生产者(消息发送方):发送请求发送消息

       ③、回到消费者(消息接收方):可以看到已接收消息成功

       ④、redis客户端再次验证:<猿医生>消息已成功被消费掉,验证成功。

                       Now ~ ~ ~写到这里,就写完了,如果有幸帮助到你,请记得关注我,共同一起见证我们的成长

  • 20
    点赞
  • 92
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

猿医生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值