项目结构
一个redistool工具包,包名无所谓
导入redis依赖和fastjson依赖
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!--redis依赖-->
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
一个配置文件redisconfig.properties(名字一样)
#redis配置
#ip
HOST=192.168.1.105
#端口
POST=6379
#登录密码
PASS=1234
然后复制Redis类
package redistool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import redis.clients.jedis.Jedis;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class Redis {
private static Jedis jedis;
private static String HOST;
private static int POST;
private static String PASS;
static{
//读取本地的自动生成的配置
InputStream is = null;
Properties pps = null;
try {
is = new FileInputStream(System.getProperty("user.dir")+"\\src\\main\\resources\\redisconfig.properties");
//加载配置文件的类
pps = new Properties();
//读取该配置文件的类
pps.load(is);
//获取对应配置文件的类的模板文件的路径,等下传入底下的路径
HOST=pps.getProperty("HOST");
POST= Integer.parseInt(pps.getProperty("POST"));
PASS=pps.getProperty("PASS");
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized static Jedis getInstance(){
if (jedis==null){
jedis = new Jedis(Redis.HOST, Redis.POST);
jedis.auth(Redis.PASS);
return jedis;
}else{
return jedis;
}
}
public static void setValue(String key,Object value){
Redis.getInstance().set(key,JSON.toJSONString(value));
}
//集合对象存储
//使用格式:List<User> us = (List<User>)Redis.getValue("test",User.class);
public static Object getArrayValue(String key,Class cla){
return JSONArray.parseArray(Redis.getInstance().get(key),cla);
}
//对象存储
public static Object getObjectValue(String key){
return JSONArray.parse(Redis.getInstance().get(key));
}
}
方法:
setValue(String key,Object value);存值
getArrarValue(String key,Class class);取值集合类型
使用方法:
List<User> us = (List<User>)Redis.getValue("test",User.class);
getObjectValue(String key);