redis概念
下载安装
https://github.com/MicrosoftArchive/redis/releases
注:官网下载的不能直接用。。用这个直接下载解压就可以。(点击里面最新版本的assets,然后msi还是zip,msi是安装流程,zip就是zip了。。)
各文件功能
先打开server,然后别关,接着打开cli输入相应指令就可以了。
比如set zhangsan hanhan,就是把键值对zhangsan(key):hanhan(value)存储进去
接着,用get zhangsan就可以查出zhangsan(key)的value。
redis的数据结构
基本命令
1.String
存储:set key value
获取:get key
删除:del key(删除key和value)
2.hash
存储:hset key field value(field:value)
获取:hget key field;获取所有:hgetall key
删除:hdel key field
3.list
存储:lpush key value(从左边加入)
rpush key value(从右边加入)
获取:lrange key start end(范围获取)
删除:lpop key(删除列表最左边的元素并将元素返回)
rpop 同理
4.set(不允许重复)
存储:sadd key value
获取:smembers key:获取set集合中所有元素
删除:srem key value
顺序不一定
5.sortedset(不允许重复并且有序)
存储:zadd key score value
获取:zrange key start end(withscores 的话可以看到分数)
zrem key value
6.keys *:查询所有key
7.type key:获取键对应的value的类型
持久化
RDB
AOF(一般不用)
Jedis
入门
@Test
public void test() {
Jedis jedis = new Jedis("localhost",6379); //不传参数的话,默认是这里面的
jedis.set("zhangsan1","hanhan");
jedis.close();
}
setex(key,seconds,value):将key:value存储进去,然后seconds后删除。。这样可以来实现存储有时限的数据
具体语法参考redis
连接池
@Test
public void test() {
JedisPool jedisPool = new JedisPool();
Jedis resource = jedisPool.getResource();
resource.set("xiaohong","haha");
resource.close();
}
工具类(类似于JDBCUtils)
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.Properties;
public class JedisUtils {
private static JedisPool jedisPool;
static {
InputStream is = JedisUtils.class.getClassLoader().getResourceAsStream("infor.properties");
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
JedisPoolConfig jdisCon = new JedisPoolConfig();
jdisCon.setMaxTotal(Integer.parseInt(properties.getProperty("maxNum")));
jedisPool = new JedisPool(jdisCon,properties.getProperty("host"),Integer.parseInt(properties.getProperty("port")));
}
public static Jedis jedisReour(JedisPool jedisPool) {
return jedisPool.getResource();
}
}
当然这里的properties需要自己去指定,比如用到的maxNum,host(localhost),以及port(端口)。