数据库:redis(三)

redis入门篇数据库:redis(一)
java代码操作redis数据库:redis(二)

本篇:redis连接池(自带的JedisPool)与案例。
redis连接池:

public class TestRedisPool {
	@Test
	public void test7() {
		JedisPoolConfig cfg=new JedisPoolConfig();//配置对象
		cfg.setMaxTotal(50);
		cfg.setMaxIdle(10);
		//以上三步可以不用写 直接用默认值		
		JedisPool jdsp=new JedisPool(cfg,"127.0.0.1",6379);//连接池对象
		Jedis jds=jdsp.getResource();//获取连接
		//省略数据库操作
		jds.close();//归还连接池
	}
}

抽取工具类:
jedis.properties:

host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10

JedisPoolUtils.java:

public class JedisPoolUtils {
	private static JedisPool jdsp;
	
	static {
		//类加载时读取配置文件
		InputStream ips=JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
		Properties pro =new Properties();
		try {
			pro.load(ips);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//获取数据
		JedisPoolConfig cfg=new JedisPoolConfig();
		cfg.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
		cfg.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
		
		jdsp= new JedisPool(cfg, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
	}
	
	public static Jedis getJedis() {
		return jdsp.getResource();
	}
}
public class TestJdsUtils {
	public static void main(String[] args) {
		Jedis jds=JedisPoolUtils.getJedis();
		
		jds.set("hello", "good game");
		System.out.println(jds.get("hello"));
		jds.close();
	}
}

测试成功:
在这里插入图片描述
一个小案例:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值