package com.wsd;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class Redis {
public static void main(String[] args) {
//读取properties file
String fileName = "redis.properties";
Map<String,String> map = getProperties(fileName);
String host = map.get("host");
int port = Integer.valueOf( map.get("port") );
String auth = map.get("auth");
int select = Integer.valueOf( map.get("select") );
//Jedis 连接池的配置类,它用于配置连接池的行为和属性
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(5); // 最大连接数
poolConfig.setMaxIdle(3); // 最大空闲连接数
poolConfig.setMinIdle(1); // 最小空闲连接数
//创建jedis连接池
JedisPool jedisPool = new JedisPool(poolConfig,host,port,3000,auth,select);
//从连接池获取连接
Jedis jedis = jedisPool.getResource();
//执行set命令
String OK = jedis.set("name","罗小白");
System.out.println(OK);
//执行get命令
String name = jedis.get("name");
System.out.println("name=" + name);
if(jedis != null)
jedis.close();
}
private static Map<String,String> getProperties(String fileName){
Map<String,String> map = new HashMap<>();
Properties properties = new Properties();
InputStream inputStream = null;
try{
//读取properties file
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
properties.load(inputStream);
String host = properties.getProperty("host");
String port = properties.getProperty("port");
String auth = properties.getProperty("auth");
String select = properties.getProperty("select");
map.put("host",host);
map.put("port",port);
map.put("auth",auth);
map.put("select",select);
}catch (IOException ex){
System.out.println("read file:" + fileName + " fail");
}finally {
if(inputStream != null);
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
}