JedisPool的构造器如下:
public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port) { this(poolConfig, host, port, 2000, (String)null, 0, (String)null); }
创建jedis的配置文件:jedis.properties
jedis.host=192.168.40.130
jedis.port=6379
jedis.maxTotal=50
jedis.maxIdle=10
创建JedisUtils:com.itheima.util.JedisUtils,使用静态代码块初始化资源
public class JedisUtils { private static int maxTotal; private static int maxIdel; private static String host; private static int port; private static JedisPoolConfig jpc; private static JedisPool jp; static { ResourceBundle bundle = ResourceBundle.getBundle("redis"); // 最大连接数 maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal")); // 默认连接数 maxIdel = Integer.parseInt(bundle.getString("redis.maxIdel")); // ip地址 host = bundle.getString("redis.host"); // 端口号 port = Integer.parseInt(bundle.getString("redis.port")); //Jedis连接池配置 jpc = new JedisPoolConfig(); jpc.setMaxTotal(maxTotal); jpc.setMaxIdle(maxIdel); jp = new JedisPool(jpc,host,port); } public static Jedis getJedis(){ // 连接池对象 Jedis jedis = jedisPool.getResource(); return jedis; } }
import com.util.JedisUtils; import redis.clients.jedis.Jedis; import java.util.ResourceBundle; public class JedisTest { public static void main(String[] args) { Jedis jedis = JedisUtils.getJedis(); jedis.set("name","Tom"); String name= jedis.get("name"); System.out.println(name); jedis.close(); } }