在Java中操作Redis

在java中如何操作redis呢

使用jedis,Jedis 是 Redis 官方首选的 Java 客户端开发包\

使用jedis

下载

<dependency>
	<groupId>redis.clients</groupId>
		<artifactId>jedis</artifactId>
	<version>3.5.1</version>
</dependency>

hello world

final static String URL = "localhost";
final static int PORT = 6379;

@Test
	public void test_String() {

		// 1.连接jedis
		Jedis jedis = new Jedis(URL, PORT);

		// 2.存取数据
		jedis.set("name", "itheima");
		String name = jedis.get("name");
		System.out.println(name);

		// 3.关闭资源
		jedis.close();
	}

jedis pool

jedis为我们提供了jedispool(连接池)对象
我们可以从连接池中获取jedis对象

public class RedisFactory {

	/**
	 * redis config文件的名称 默认从classpath下加载
	 */
	final static String CONFIG_NAME = "redis_config.properties";

	private static RedisFactory factory;

	private JedisPool pool;

	private RedisFactory() {
		factory = this;
		try {
			// 从属性文件中加载数据
			InputStream in = RedisFactory.class.getClassLoader().getResourceAsStream(CONFIG_NAME);
			Properties reader = new Properties();
			reader.load(in);
			// 指定连接的端口号
			Integer port = Integer.parseInt(reader.getProperty("redis.connect.port"));
			// 指定连接的地址
			String address = reader.getProperty("redis.connect.address");
			// 链接池中最大连接数
			Integer maxActive = Integer.parseInt(reader.getProperty("redis.connect.maxActive"));
			// 链接池中最大空闲的连接数
			Integer maxIdle = Integer.parseInt(reader.getProperty("redis.connect.maxIdle"));
			// 链接池中最小空闲的连接数
			Integer minIdle = Integer.parseInt(reader.getProperty("redis.connect.minIdle"));

			// pool详细配置都可以通过JedisPoolConfig来实现
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(maxActive);
			config.setMaxIdle(maxIdle);
			config.setMinIdle(minIdle);

			this.pool = new JedisPool(config, address, port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static RedisFactory newInstance() {
		return factory == null ? new RedisFactory() : factory;
	}

	/**
	 * 通过jedis pool获取jedis实例对象
	 * 
	 * @return
	 */
	public Jedis getResource() {

		return this.pool.getResource();
	}

}

配置文件redis_config.properties

# redis server连接参数
## 连接的端口号
redis.connect.port=6379
## 连接的地址
redis.connect.address=localhost:
## 链接池中最大连接数
redis.connect.maxActive=20
## 链接池中最大空闲的连接数
redis.connect.maxIdle=20
## 链接池中最少空闲的连接数
redis.connect.minIdle=20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值