使用java代码连接redis及工具類

一.导包

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

二.开始测试

	@Test
	public void testName() throws Exception {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
//		最大连接数
		poolConfig.setMaxTotal(50);
		//最大空闲连接
		poolConfig.setMaxIdle(10);
		//最小空闲连接
		poolConfig.setMinIdle(5);
		poolConfig.setTestOnCreate(true); //创建连接的时候需要先进行测试连接是否可用
		poolConfig.setTestOnReturn(true);//返还连接的时候需要先测试
		//连接超时
		poolConfig.setMaxWaitMillis(1);
		//获取连接池
		JedisPool jedisPool=new JedisPool(poolConfig, "192.168.89.250", 6379, 3000);
		//获得连接
		Jedis jedis = jedisPool.getResource();
		//在redis中设置参数
		jedis.set("mykey", "hello1");
		//在redis中获取参数
		String string = jedis.get("setkey");
		System.out.println(string);
		//记得关闭
		jedis.close();
		
	}

三.封装到before中

	Jedis jedis;
	
	@Before
	public void testName1() throws Exception {
		JedisPoolConfig poolConfig = new JedisPoolConfig();
//		最大连接数
poolConfig.setMaxTotal(50);//最大空闲连接poolConfig.setMaxIdle(10);//最小空闲连接poolConfig.setMinIdle(5);poolConfig.setTestOnCreate(true); //创建连接的时候需要先进行测试连接是否可用poolConfig.setTestOnReturn(true);//返还连接的时候需要先测试//连接超时poolConfig.setMaxWaitMillis(1);//获取连接池JedisPool jedisPool=new JedisPool(poolConfig, "192.168.89.250", 6379, 3000);//获得连接jedis = jedisPool.getResource();}

四.封装到工具类中,调用工具类获取连接(☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆)

package cn.itcast.spider.uitl;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {

	private static JedisPool jedisPool;

	public static JedisPool getjedispool() {
		if (null == jedisPool) {

			// 数据库连接池配置信息
			JedisPoolConfig poolConfig = new JedisPoolConfig();
			poolConfig.setMaxTotal(50);
			poolConfig.setMaxIdle(10);
			poolConfig.setMinIdle(5);
			poolConfig.setTestOnCreate(true); // 创建连接的时候需要先进行测试连接是否可用
			poolConfig.setTestOnReturn(true);// 返还连接的时候需要先测试
			poolConfig.setMaxWaitMillis(1);
			// 获得连接redis的连接池的连接
			jedisPool = new JedisPool(poolConfig, "192.168.89.250", 6379, 3000);

			return jedisPool;
		} else {
			// 如果连接不为空,就使用原来的连接;
			return jedisPool;
		}
	}

	// 从连接池里面获取一个连接
	public static Jedis getjedis() {
		JedisPool getjedispool = getjedispool();
		Jedis jedis = getjedispool.getResource();
		return jedis;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值