JedisUtils 对jedis的封装 and RedisCacheManager 管理多个连接池

本文档展示了如何使用Java实现Redis缓存的管理类`RedisCacheManager`,以及一个简单的Jedis工具类`JedisUtils`。`RedisCacheManager`通过配置多个数据库连接,并提供获取和归还资源的方法。`JedisUtils`提供了如获取、设置、删除等基本操作,方便进行Redis的CRUD操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RedisCacheManager

import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;
@Service("redisCacheManager")// @Slf4jpublic class RedisCacheManager {  @Value("${redisdbtype}")  private String redisdbtype;    @Value("${redisdbnumber}")  private String redisdbnumber;    @Value("${host}")  private String host;  @Value("${port}")  private int port;  @Value("${timeout}")  private int timeout;  @Value("${passwords}")  private String passwords;    @Value("${maxtotal}")  private String maxtotal;  @Value("${maxidle}")  private String maxidle;  @Value("${minidle}")  private String minidle;  @Value("${maxwaitmillis}")  private String maxwaitmillis;  @Value("${testonborrow}")  private String testonborrow;  @Value("${testwhileidle}")  private String testwhileidle;    private static JedisPoolConfig poolConfig = null;    // 保存不同的数据库连接  private ConcurrentHashMap<String, RedisCachePool> redisPoolMap = new ConcurrentHashMap<String, RedisCachePool>();    public ConcurrentHashMap<String, RedisCachePool> getRedisPoolMap() {    if (redisPoolMap.size() < 1) {      initConfig();      initPoolMap();    }    return redisPoolMap;  }    /**   * @Description:共享的poolconfig   * @return:void   */  private void initConfig() {    poolConfig = new JedisPoolConfig();    poolConfig.setTestOnBorrow(testwhileidle.equals("true") ? true : false);    poolConfig.setTestWhileIdle(testonborrow.equals("true") ? true : false);    poolConfig.setMaxIdle(Integer.parseInt(maxidle));    poolConfig.setMaxTotal(Integer.parseInt(maxtotal));    poolConfig.setMinIdle(Integer.parseInt(minidle));    poolConfig.setMaxWaitMillis(Integer.parseInt(maxwaitmillis));  }    private void initPoolMap() {    try {      if (null != redisdbtype && null != redisdbnumber) {        String[] dbs = redisdbtype.split(",");        String[] numbers = redisdbnumber.split(",");        for (int i = 0; i < dbs.length; i++) {          // 得到redis连接池对象          JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, passwords);          // 存放不同redis数据库          redisPoolMap.put(dbs[i], new RedisCachePool(Integer.parseInt(numbers[i]), jedisPool));        }      }    } catch (Exception e) {      // log.error("redisCacheManager初始化失败!" + e.getLocalizedMessage());    }  }    /**   * @Description: 得到jedis连接   * @param dbtypeName   * @return:Jedis   */  public Jedis getResource(RedisDataBaseType dbtypeName) {    Jedis jedisResource = null;    RedisCachePool pool = redisPoolMap.get(dbtypeName.toString());    if (pool != null) {      jedisResource = pool.getResource();    }    return jedisResource;  }    /**   * @Description: 返回连接池   * @param dbtypeName   * @param jedis   * @return:void   */  public void returnResource(RedisDataBaseType dbtypeName, Jedis jedis) {    RedisCachePool pool = redisPoolMap.get(dbtypeName.toString());    if (pool != null)      pool.returnResource(jedis);  }}

JedisUtils

import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import redis.clients.jedis.exceptions.JedisException;
import java.util.List;import java.util.Map;
/** * @author Loger * Date: 2018-07-30 * TIme: 23:54 * Description : */public class JedisUtils {
    private static JedisPoolConfig config;
    private static JedisPool jedisPool;
    private static String password = "xxxxxxxxxx";
    static {        config = new JedisPoolConfig();        config.setMaxIdle(100);        config.setMaxIdle(10);        jedisPool = new JedisPool(config, "192.168.113.128", 6379);    }
    /**     * 获取jedis     *     * @return     */    public static Jedis getJedis() {        Jedis jedis = jedisPool.getResource();        jedis.auth(password);        return jedis;    }
    /**     * jedis放回连接池     *     * @param jedis     */    public static void close(Jedis jedis) {        //从源码可以分析得到,如果是使用连接池的形式,这个并非真正的close,而是把连接放回连接池中        if (jedis != null) {            jedis.close();        }    }
    /**     * get     *     * @param key     * @return     */    public static String get(String key) {        Jedis jedis = null;        try {            jedis = getJedis();            return jedis.get(key);        } catch (Exception e) {            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        } finally {            close(jedis);        }    }
    /**     * set     *     * @param key     * @param value     * @return     */    public static void set(String key, String value) {        Jedis jedis = null;        try {            jedis = getJedis();            jedis.set(key, value);        } catch (Exception e) {            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        } finally {            close(jedis);        }    }
    /**     * set with expire milliseconds     *     * @param key     * @param value     * @param seconds     * @return     */    public static void set(String key, String value, long seconds) {        Jedis jedis = null;        try {            jedis = getJedis();            //* @param nxxx NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the key            //     *                     *          if it already exist.            //     *                     * @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds            jedis.set(key, value, "NX", "EX", seconds);        } catch (Exception e) {            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        } finally {            close(jedis);        }    }

    public static Long incr(String key){        Jedis jedis = null;        try {            jedis = getJedis();            return jedis.incr(key);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    public static void hset(String key,String field,String value){        Jedis jedis = null;        try {            jedis = getJedis();            jedis.hset(key,field,value);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    public static String hget(String key,String field){        Jedis jedis = null;        try {            jedis = getJedis();            return jedis.hget(key,field);        }catch (Exception e){            e.printStackTrace();        }finally {            close(jedis);        }        return null;    }
    public static Map<String,String> hgetAll(String key){        Jedis jedis = null;        try {            jedis = getJedis();            return jedis.hgetAll(key);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    /**     *     * @param timeout 0表示永久 单位秒     * @param key key     * @return [key,value]     */    public static String blpop(int timeout,String key){        Jedis jedis = null;        try {            jedis = getJedis();            List<String> list = jedis.blpop(timeout, key);            return list.get(1);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    public static String blpop(String key){        Jedis jedis = null;        try {            jedis = getJedis();            List<String> list = jedis.blpop(0, key);            return list.get(1);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    public static void lpush(String key,String... value){        Jedis jedis = null;        try {            jedis = getJedis();            jedis.lpush(key,value);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }    }
    /**     *     * @param timeout 0表示永久 单位秒     * @param key key     * @return [key,value]     */    public static String brpop(int timeout,String key){        Jedis jedis = null;        try {            jedis = getJedis();            List<String> list = jedis.brpop(timeout, key);            return list.get(1);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    public static String brpop(String key){        Jedis jedis = null;        try {            jedis = getJedis();            List<String> list = jedis.brpop(0, key);            return list.get(1);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }finally {            close(jedis);        }    }
    public static void rpush(String key,String... value){        Jedis jedis = null;        try {            jedis = getJedis();            jedis.rpush(key,value);        }catch (Exception e){            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        }    }
    /**     * 获取key过期时间 -1表示永久 -2表示该key不存在     * @param key     * @return     */    public static long ttl(String key) {        Jedis jedis = null;        try {            jedis = getJedis();            return jedis.ttl(key);        } catch (Exception e) {            e.printStackTrace();            throw new JedisException(e.getMessage(),e);        } finally {            close(jedis);        }    }}

更多学习资料 请关注微信公众号

个人学习微信公众号

 

 

### 大模型对齐微调DPO方法详解 #### DPO简介 直接偏好优化(Direct Preference Optimization, DPO)是一种用于改进大型语言模型行为的技术,该技术通过结合奖励模型训练和强化学习来提升训练效率与稳定性[^1]。 #### 实现机制 DPO的核心在于它能够依据人类反馈调整模型输出的概率分布。具体来说,当给定一对候选响应时,DPO试图使更受偏好的那个选项具有更高的生成概率。这种方法不仅简化了传统强化学习所需的复杂环境设置,而且显著增强了模型对于多样化指令的理解能力和执行精度[^2]。 #### PAI平台上的实践指南 为了便于开发者实施这一先进理念,在PAI-QuickStart框架下提供了详尽的操作手册。这份文档覆盖了从环境配置直至完成整个微调流程所需的一切细节,包括但不限于数据准备、参数设定以及性能评估等方面的内容。尤其值得注意的是,针对阿里云最新发布的开源LLM——Qwen2系列,文中给出了具体的实例说明,使得即使是初次接触此类工作的用户也能顺利上手。 ```python from transformers import AutoModelForCausalLM, Trainer, TrainingArguments model_name_or_path = "qwen-model-name" tokenizer_name = model_name_or_path training_args = TrainingArguments( output_dir="./results", per_device_train_batch_size=8, num_train_epochs=3, ) trainer = Trainer( model_init=lambda: AutoModelForCausalLM.from_pretrained(model_name_or_path), args=training_args, train_dataset=train_dataset, ) # 假设已经定义好了train_dataset trainer.train() ``` 这段代码片段展示了如何使用Hugging Face库加载预训练模型并对其进行微调的过程。虽然这里展示的例子并不完全对应于DPO的具体实现方式,但它提供了一个基础模板供进一步定制化开发之用[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值