美文网首页
Java-Jedis连接池简单封装

Java-Jedis连接池简单封装

作者: Wannay | 来源:发表于2021-01-20 17:32 被阅读0次

1.读取Yaml配置文件的工具类,可以通过类路径和文件系统路径进行读取

package com.example.demopro.utils;

import com.example.demopro.DemoproApplication;
import org.omg.CORBA.portable.InputStream;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RedisUtils {
    public Map YamlReadJedisConfigFromResource(String path) {
        Yaml yaml = new Yaml();
        Map map = (Map) yaml.load(DemoproApplication.class.getResourceAsStream(path));
        Map map2 = (Map) ((Map) map.get("jedis")).get("pool");  //得到配置文件
        return map2;
    }

    public Map YamlReadJedisConfig(String path) throws FileNotFoundException {
        Yaml yaml = new Yaml();  //创建yaml对象
        Map map = (Map) yaml.load(new FileInputStream(path));  //根据路径读取文件
        Map map2 = (Map) ((Map) map.get("jedis")).get("pool");  //得到配置文件
        return map2;
    }

    public Map LoadJedisConfig() {  //固定配置写在这里
        Map<String, Object> map = new HashMap<>();
        map.put("host", "127.0.0.1");
        map.put("password", 123456);
        map.put("port", 6379);
        map.put("timeout", 5000);
        map.put("db", 2);
        map.put("max-active", 5000);
        map.put("max-idle", 1000);
        map.put("max-wait", 5000);
        map.put("testOnBorrow", true);
        map.put("testOnReturn", true);
        return map;
    }
}

2.Jedis连接池类

package com.example.demopro.utils;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;

@Component
public class JedisPoolUtils {
    private static String host;  //Redis Server Host
    private static Integer port;  //Redis Server Port
    private static String password;  //Redis Server Password
    private static int timeout;  //Redis Time to Out
    private static int db;  //数据库序号
    private static int maxActive;  //最大激活数量
    private static int maxIdle; //最大Idle
    private static int maxWait;  //最大等待时间
    private static boolean testOnBorrow;
    private static boolean testOnReturn;
    private static final JedisPool pool;  //jedis连接池

    static {   //这里要异常处理
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        try {
            String yaml_class_path = "/application.yaml";  //yaml文件的类路径
            RedisUtils redisUtils = new RedisUtils();  //导入读取Yaml配置文件的类
            Map map = redisUtils.YamlReadJedisConfigFromResource(yaml_class_path);

            host = map.get("host") == null ? "127.0.0.1" : (String) map.get("host");
            port = map.get("port") == null ? 6379 : (Integer) map.get("port");
            password = String.valueOf(map.get("password"));
            timeout = map.get("timeout") == null ? 5000 : (Integer) map.get("timeout");
            db = map.get("db") == null ? 0 : (Integer) map.get("db");
            maxActive = map.get("max-active") == null ? 5000 : (Integer) map.get("max-active");
            maxIdle = map.get("max-active") == null ? 2000 : (Integer) map.get("max-idle");
            maxWait = map.get("max-wait") == null ? 5000 : (Integer) map.get("max-wait");
            testOnBorrow = map.get("testOnBorrow") == null ? true : (boolean) map.get("testOnBorrow");
            testOnReturn = map.get("testOnReturn") == null ? true : (boolean) map.get("testOnReturn");

            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setTestOnBorrow(testOnBorrow);
            jedisPoolConfig.setTestOnReturn(testOnReturn);
            jedisPoolConfig.setMaxWaitMillis(maxWait);
            jedisPoolConfig.setMaxTotal(maxActive);

        } catch (Exception ex) {
            System.out.println("连接池创建失败" + ex.getMessage());
        }

        pool = new JedisPool(jedisPoolConfig, host, port, timeout, password, db);

    }

    //获取Jedis连接
    public Jedis GetJedisConn() {  //获取Jedis连接
        return pool.getResource();
    }

    //归还Jedis连接
    public void ReturnJedisConn(Jedis jedis) {  //归还连接
        pool.returnResourceObject(jedis);
    }

}


3.RedisService
接口

package com.example.demopro.service;

public interface RedisService {
    public String get(String key);  //get
    public String set(String key,String value);  //set
    public String set(String key,String value,int seconds);  //set
    public Long del(String key);  //del
    public Long setExpire(String key,int seconds);  //setExpire
}

实现类

package com.example.demopro.service.Impl;

import com.example.demopro.service.RedisService;
import com.example.demopro.utils.JedisPoolUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import javax.annotation.Resource;

@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    private JedisPoolUtils jedisPoolUtils;  //注入连接池

    @Override
    public String get(String key){

        Jedis jedis = jedisPoolUtils.GetJedisConn();  //从连接池获取连接
        String result = jedis.get(key);
        jedisPoolUtils.ReturnJedisConn(jedis); //归还连接给连接池
        return result;
    }

    @Override
    public String set(String key,String value){
        Jedis jedis = jedisPoolUtils.GetJedisConn();  //从连接池获取连接
        String result = jedis.set(key,value);
        jedisPoolUtils.ReturnJedisConn(jedis); //归还连接给连接池
        return result;
    }

    @Override
    public Long del(String key){
        Jedis jedis = jedisPoolUtils.GetJedisConn();  //从连接池获取连接
        Long result = jedis.del(key);
        jedisPoolUtils.ReturnJedisConn(jedis); //归还连接给连接池
        return result;
    }

    @Override
    public Long setExpire(String key,int seconds){
        Jedis jedis = jedisPoolUtils.GetJedisConn();  //从连接池获取连接
        Long result = jedis.expire(key,seconds);
        jedisPoolUtils.ReturnJedisConn(jedis); //归还连接给连接池
        return result;
    }

    @Override
    public String set(String key,String value,int seconds){
        Jedis jedis = jedisPoolUtils.GetJedisConn();  //从连接池获取连接
        String result = jedis.set(key,value);
        jedis.expire(key, seconds);
        jedisPoolUtils.ReturnJedisConn(jedis); //归还连接给连接池
        return result;
    }

}

4.application.yaml文件

jedis:
  pool:
    host: 127.0.0.1 #host
    password: 123456 #password
    port: 6379 #port
    timeout: 5000 #timeout
    db: 2 #db
    max-active: 5000  # jedis最大活跃数目
    max-idle: 1000  # jedis最大保存idle状态对象数
    max-wait: 5000  # 最大等待时间
    testOnBorrow: true  # jedis调用borrowObject方法时,是否进行有效检查
    testOnReturn: true  # jedis调用returnObject方法时,是否进行有效检查

5.需要注意的是:在Service中不能使用jedis.close(),不然会出现如下报错

redis.clients.jedis.exceptions.JedisException: Could not return the resource

相关文章

网友评论

      本文标题:Java-Jedis连接池简单封装

      本文链接:https://www.haomeiwen.com/subject/bhnkzktx.html