Redis的消息订阅/发布 Utils工具类

package cn.cicoding.utils;

import org.json.JSONException;
import org.json.JSONObject;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisConnectionException;

class MQClient {
    public static final int MSG_REALTIME = 1;
    public static final int MSG_CACHED = 2;
    public static final int MSG_SERIALIZABLE = 3;
    public static final String NOTIFY_CHANNEL = "ClientNotify";

    private JedisPool pool;
    private boolean exit;
    private JedisPubSub pubsub;

    public MQClient(String ip, int port, JedisPubSub pubsub) {
        JedisPoolConfig config = new JedisPoolConfig();   
        config.setMaxWaitMillis(10 * 1000);  
        config.setMaxIdle(1000);  
        config.setTestOnBorrow(true);  
        pool = new JedisPool(config, ip, port, Protocol.DEFAULT_TIMEOUT, null);
        exit = false;
        this.pubsub = pubsub;
    }

    public boolean publish(String channels, String message, String content) {
        JSONObject obj = new JSONObject();
        boolean ret = false;
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            if (message != null) {
                obj.put("message", message);
            }
            try {
                JSONObject objCon = new JSONObject(content);
                obj.put("content", objCon);
            } catch (JSONException e) {
                obj.put("content", content);
            }
            String[] tmp = channels.split(";");
            for (String channel : tmp) {
                try {
                    if (jedis.publish(channel, obj.toString()) > 0) {
                        ret = true;
                    }
                } catch (Exception e) {
                    break;
                }
            }
        } catch (JSONException e) {
        } finally {
            if (jedis != null){
                jedis.close();
            }
        }

        return ret;
    }

    public boolean clientNotify(String clients, String message, String content, int type) {
        if (type == MSG_REALTIME) {
            return publish(clients, message, content);
        }

        boolean ret = false;

        try {
            JSONObject obj = new JSONObject();
            obj.put("clients", clients);
            obj.put("type", type);
            if (message != null) {
                obj.put("message", message);
            }
            try {
                JSONObject objCon = new JSONObject(content);
                obj.put("content", objCon);
            } catch (JSONException e) {
                obj.put("content", content);
            }

            if (pool.getResource().publish(NOTIFY_CHANNEL, obj.toString()) > 0) {
                ret = true;
            }
        } catch (JSONException e) {
        }

        return ret;
    }

    public boolean setValue(String key, String value) {
        try {
            String response = pool.getResource().set(key, value);
            if (response != null && response.equals("OK")) {
                return true;
            }
        } catch (JedisConnectionException e) {
            e.printStackTrace();
        }

        return false;
    }

    public String getValue(String key) {
        return pool.getResource().get(key);
    }

    public void subscribe(String... channels) {
        while (!exit) {
            try {
                pool.getResource().subscribe(pubsub, channels);
            } catch (JedisConnectionException e) {
                e.printStackTrace();
                System.out.println("try reconnect");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

Test测试函数:

package cn.cicoding.utils;

import redis.clients.jedis.JedisPubSub;

public class Test extends JedisPubSub {
    @Override
    public void onMessage(String channel, String message) {
        System.out.println(channel + ":" + message);
    }

    public static void main(String[] args) {
        MQClient client = new MQClient("127.0.0.1", 6379, new Test());
        client.setValue("abc", "java setted");
        System.out.println(client.getValue("abc"));
        System.out.println(client.clientNotify("nodeSubscriber", "message from java", "{\"debug\":0}", MQClient.MSG_REALTIME));
        client.subscribe("testInitiativePerception");
    }
}

 

转载于:https://www.cnblogs.com/zhaokejin/p/9630069.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个基于 RedisTemplate 的 Redis 工具类 RedisUtils 的实现,提供了一些常见的 Redis 操作方法,包括读取、写入、过期时间等。 ```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component public class RedisUtils { private final RedisTemplate<String, Object> redisTemplate; public RedisUtils(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public void set(String key, Object value, long timeout, TimeUnit timeUnit) { redisTemplate.opsForValue().set(key, value, timeout, timeUnit); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public boolean delete(String key) { return redisTemplate.delete(key); } public boolean expire(String key, long timeout, TimeUnit timeUnit) { return redisTemplate.expire(key, timeout, timeUnit); } } ``` 使用时,只需要通过构造函数注入 RedisTemplate 对象,然后使用 RedisUtils 提供的方法即可完成对 Redis 数据库的操作。例如: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private RedisUtils redisUtils; public void example() { String key = "example_key"; String value = "example_value"; // 使用 RedisTemplate 直接写入 redisTemplate.opsForValue().set(key, value); // 使用 RedisUtils 封装后的写入 redisUtils.set(key, value); // 使用 RedisUtils 封装后的读取 Object result = redisUtils.get(key); // 使用 RedisUtils 封装后的删除 boolean deleted = redisUtils.delete(key); // 使用 RedisUtils 封装后的设置过期时间 boolean expired = redisUtils.expire(key, 5, TimeUnit.MINUTES); } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值