RedisUtils(自定义线程池)

maven依赖

	<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
	<dependency>
	    <groupId>redis.clients</groupId>
	    <artifactId>jedis</artifactId>
	    <version>3.3.0</version>
	</dependency>

完整代码

package com.xyulu.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * @Author Xyulu
 * @Date 2021/3/10 10:35
 * @Version 1.0
 */
public class RedisUtil {

    private final static Logger log = LoggerFactory.getLogger(RedisUtil.class);

    private static RedisUtil instance;
    private JedisPoolConfig config;
    private JedisPool pool;

    public static RedisUtil getInstance() {
        if (instance == null) {
            synchronized (RedisUtil.class) {
                if (instance == null) {
                    instance = new RedisUtil();
                    instance.init();
                }
            }
        }
        return instance;
    }

    private void init() {
        String ip = "127.0.0.1";
        int port = 6379;
        String auth = "123ABCdef*";
        int timeOut = 1000;

        config = new JedisPoolConfig();
        config.setMaxIdle(10); // 控制pool中最多有多少个连接给空闲状态
        config.setMaxTotal(20); // 控制pool中最大连接实例
        config.setMaxWaitMillis(1000); // 最大超时等待时间(毫秒)
        config.setTestOnBorrow(true); // 获取连接提前验证
        config.setTestOnReturn(true); // 归还连接提前验证
        pool = new JedisPool(config,ip,port,timeOut,auth);
    }

    /**
     * 获取Jedis
     * @return Jedis
     */
    public Jedis getClient(){
        if (pool == null) {
            init();
        }
        return pool.getResource();
    }

    /**
     * 关闭jedis连接池
     * @param jedis
     */
    private void returnJedis (Jedis jedis) {
        if (jedis != null){
            try{
                jedis.close();
            }catch (Exception e){
                log.error("Jedis关闭异常,ecxeption is {}",e);
            }
        }
    }

    public String set(String key, String value) {
        String result = null;
        if (pool == null) {
            init();
        }
        Jedis resource = pool.getResource();
        try {
            result = resource.set(key, value);
        } catch (Exception e) {
            log.error("set key is error ,exception is {}",e);
        } finally {
            if (resource != null) {
                resource.close();
            }
        }
        return result;
    }

    public String get (String key) {
        String value = null;
        if (pool == null) {
            init();
        }
        Jedis resource = pool.getResource();
        try {
            value = resource.get(key);
        } catch (Exception e) {
            log.error("get value is error ,exception is {}",e);
        } finally {
            if (resource != null) {
                resource.close();
            }
        }
        return value;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Redis 本身是单线程的,但是在某些情况下,我们需要在 Redis 中使用线程池来执行一些异步任务,例如在 Redis 中使用 Lua 脚本执行一些耗时的操作,或者使用 Redis 的 PUB/SUB 功能等。 Redis线程池是通过 hiredis 库来实现的,hiredis 是一个 C 语言编写的 Redis 客户端库,支持异步 IO 和线程池。 下面是一个示例代码,演示如何在 Redis 中使用线程池: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <hiredis/hiredis.h> #include <hiredis/async.h> void callback(redisAsyncContext *c, void *reply, void *privdata) { redisReply *r = reply; if (reply == NULL) return; printf("Reply: %s\n", r->str); } int main(int argc, char **argv) { const char *hostname = "127.0.0.1"; int port = 6379; struct timeval timeout = { 1, 500000 }; // 1.5 seconds redisAsyncContext *ac = redisAsyncConnect(hostname, port); if (ac->err) { printf("Error: %s\n", ac->errstr); return 1; } redisLibeventAttach(ac, EV_DEFAULT); // 绑定事件循环 redisAsyncCommand(ac, callback, NULL, "SET key value"); redisAsyncCommand(ac, callback, NULL, "GET key"); event_base_dispatch(EV_DEFAULT); // 启动事件循环,等待回调执行完成 return 0; } ``` 在这个示例中,我们使用 redisAsyncConnect() 函数连接到 Redis 服务器,使用 redisLibeventAttach() 函数将 Redis 异步上下文对象绑定到事件循环中,使用 redisAsyncCommand() 函数向 Redis 发送命令,并指定回调函数 callback 来处理命令的结果。 最后,通过调用 event_base_dispatch() 函数启动事件循环,等待回调函数执行完成。 需要注意的是,在使用 Redis线程池时,我们需要将 Redis 异步上下文对象绑定到事件循环中,否则回调函数无法执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值