3Redis与Java的集成

Posted *King*

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3Redis与Java的集成相关的知识,希望对你有一定的参考价值。

1、Maven配置

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>3.6.3</version>
</dependency>

2、application.properties配置文件

# Redis服务器地址
redis.host=1.15.106.108
# Redis服务器连接端口
redis.port=6379
# Redis服务器连接密码(默认为空)
redis.password=null
redis.timeout=30000
# 连接池最大连接数(使用负值表示没有限制)
redis.maxTotal=30
# 连接池中的最大空闲连接
redis.maxIdle=10
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.minEvictableIdleTimeMillis=1800000
redis.softMinEvictableIdleTimeMillis=10000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.maxWaitMillis=1500
redis.testOnBorrow=true
redis.testWhileIdle=true
redis.blockWhenExhausted=false
redis.JmxEnabled=true

3、RedisConfig

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@PropertySource("classpath:application.properties")
public class RedisConfig {
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private int port;
    @Value("${redis.timeout}")
    private int timeout;
    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.blockWhenExhausted}")
    private Boolean blockWhenExhausted;
    @Value("${redis.JmxEnabled}")
    private Boolean jmxEnabled;

    @Bean
    public JedisPool jedisPoolFactory(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        //连接耗尽时是否阻塞,false报异常,true阻塞直到超时,默认为true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        //是否启用pool的jmx管理功能,默认为true
        jedisPoolConfig.setJmxEnabled(jmxEnabled);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,host,port,timeout);
        return jedisPool;
    }
}

4、List实现消息简单的队列

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@Component
public class ListVer{
    public final static String RS_LIST_MQ_NS = "rlm:";

    @Autowired
    private JedisPool jedisPool;

    /*消费者接受消息*/
    public List<String> get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.brpop(0,RS_LIST_MQ_NS +key);
        } catch (Exception e) {
            throw new RuntimeException("接受消息失败!");
        } finally {
            jedis.close();
        }
    }

    /*生产者发送消息*/
    public void put(String key, String message) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.lpush(RS_LIST_MQ_NS+key,message);
        } catch (Exception e) {
            throw new RuntimeException("发送消息失败!");
        } finally {
            jedis.close();
        }
    }
}

5、测试类

import cn.enjoyedu.redis.redismq.ListVer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;

@SpringBootTest
public class TestListVer {
    @Autowired
    private ListVer listVer;

    @Test
    void testGet(){
        List<String> result = listVer.get("listmq");
        for(String message : result){
            System.out.println(message);
        }
    }

    @Test
    void testPut(){
        listVer.put("listmq","msgtest");
    }
}

6、测试结果

7、有序集合ZSET实现消息队列

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class ZSetVer {
    public final static String RS_ZS_MQ_NS = "rzsm:";

    @Autowired
    private JedisPool jedisPool;

    /*生产者,消息的发送,实际生产中,相关参数,
    比如订单信息,过期时间等应该传入,可以考虑将订单信息json化存入redis*/
    public void producer() {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            for (int i = 0; i < 5; i++) {
                String order_id = "000000000"+i;
                double score = System.currentTimeMillis()+(i*1000);
                jedis.zadd(RS_ZS_MQ_NS+"orderId",score, order_id);
                System.out.println("生产订单: " + order_id + " 当前时间:"
                        + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                System.out.println((3 + i) + "秒后执行");
            }
        } catch (Exception e) {
            throw new RuntimeException("生产消息失败!");
        } finally {
            jedis.close();
        }

    }

    //消费者,取订单
    public void consumerDelayMessage() {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            while (true) {
                Set<String> order = jedis.zrangeByScore(RS_ZS_MQ_NS+"orderId", 0,
                        System.currentTimeMillis(), 0,1);
                if (order == null || order.isEmpty()) {
                    System.out.println("当前没有等待的任务");
                    try {
                        TimeUnit.MICROSECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                String s = order.iterator().next();

                if (jedis.zrem(RS_ZS_MQ_NS+"orderId", s)>0) {
                    /*业务处理*/
                    System.out.println(s);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException("消费消息失败!");
        } finally {
            jedis.close();
        }
    }
}

8、测试类

import cn.enjoyedu.redis.redismq.ZSetVer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestZSetVer {

    @Autowired
    private ZSetVer zSetVer;

    @Test
    void testConsumerDelayMessage(){
        zSetVer.consumerDelayMessage();
    }

    @Test
    void testProducer(){
        zSetVer.producer();
    }

}

9、测试结果

以上是关于3Redis与Java的集成的主要内容,如果未能解决你的问题,请参考以下文章

七天玩转Redis | Day3Redis位图和GEO介绍与使用

java 代码片段

持续集成之Gitlab安装与应用

持续集成之Gitlab安装与应用

持续集成与自动化部署 - gitlab部署

Electron 应用程序可以与 java 代码集成吗?