超详细 java中redis的常用API示例

java中redis的常用API示例

1.创建maven工程模块redis

2.导入对应的依赖


    <dependencies> 
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
            <version>3.2.0version>
        dependency> 
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.62version>
        dependency>
    dependencies>

3.启动redis服务和客户端

4、编码测试:

连接redis数据库

操作命令

断开连接!

package com.demo.redis;

import redis.clients.jedis.Jedis;

/**
 * @className: TestPing
 * @description: 测试连接
 * @author:
 * @create: 
 **/

public class TestPing {
    public static void main(String[] args) {
        //1.创建jedis对象
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //
        System.out.println(jedis.ping());
        jedis.close();
    }
}

1.事务

package com.demo.redis;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @className: TestTransational
 * @description: 测试redis事务
 * @author:
 * @create: 
 **/

public class TestTransational {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //清除当前数据库的数据.默认为db0
        jedis.select(1);//选择redis数据库1
        jedis.flushDB();//清除当前数据库数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "zhangsan");
        jsonObject.put("age", "18");
        //开启事务
        Transaction multi = jedis.multi();
        String user = jsonObject.toJSONString();
        //jedis.watch(user);
        try {
            multi.set("user1", user);
            multi.set("user2", user);
            //int i = 1 / 0;//代码抛出异常事务,执行失败
            multi.exec();
        } catch (Exception e) {
            multi.discard();//如果有异常,则取消事务
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }
    }
}

2.修改密码

package com.demo.redis;

import redis.clients.jedis.Jedis;

/**
 * @className: TestPassword
 * @description: 测试密码
 * @author: 
 * @create: 
 **/

public class TestPassword {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //验证密码,如果没有设置密码这段代码省略
        //jedis.auth("root");
        jedis.connect();//连接
        jedis.disconnect();//断开连接
        jedis.select(1);
        jedis.flushDB();
        jedis.close();
    }
}

3.测试键

package com.demo.redis;

import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * @className: TestKey
 * @description: 测试键
 * @author:  
 * @create:
 **/

public class TestKey {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        System.out.println("选择redis数据库:"+jedis.select(1));
        System.out.println("清空数据当前数据库:"+jedis.flushDB());
        System.out.println("新增键值对{\"name\":\"zhangsan\"}"+jedis.set("name","zhangsan"));
        System.out.println("新增键值对{\"age\":\"18\"}"+jedis.set("age","18"));
        System.out.println("1号redis数据库的所有键如下");
        Set<String> keys = jedis.keys("*");
        System.out.println(keys);
        System.out.println("删除键name:"+jedis.del("name"));
        System.out.println("判断键name是否存在:"+jedis.exists("name"));
        System.out.println("判断键age是否存在:"+jedis.exists("age"));
        System.out.println("查看键age所存储的值的类型:"+jedis.type("age"));
        System.out.println("随机返回key空间的一个:"+jedis.randomKey());
        System.out.println("重命名key:"+jedis.rename("age","renameAge"));
        System.out.println("取出改后的renameAge:"+jedis.get("renameAge"));
        System.out.println("删除当前选择数据库中的所有key:"+jedis.flushDB());
        System.out.println("返回当前数据库中key的数目:"+jedis.dbSize());
        System.out.println("删除所有数据库中的所有key:"+jedis.flushAll());
        jedis.close();
    }
}

4.测试字符串

package com.demo.redis;

import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

/**
 * @className: TestString
 * @description: 测试String
 * @author: 
 * @create: 
 **/

public class TestString {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();
        System.out.println("===========增加数据===========");
        System.out.println(jedis.set("key1","value1"));//OK
        System.out.println(jedis.set("key2","value2"));//OK
        System.out.println(jedis.set("key3", "value3"));//OK
        System.out.println("删除键key2:"+jedis.del("key2"));//删除键key2:1
        System.out.println("获取键key2:"+jedis.get("key2"));//获取键key2:null
        System.out.println("修改key1:"+jedis.set("key1", "value1Changed"));//修改key1:OK
        System.out.println("获取key1的值:"+jedis.get("key1"));//获取key1的值:value1Changed
        System.out.println("在key3后面加入值:"+jedis.append("key3", "End"));//在key3后面加入值:9
        System.out.println("key3的值:"+jedis.get("key3"));//key3的值:value3End
        System.out.println("增加多个键值对:"+jedis.mset("key01","value01","key02","value02","key03","value03"));//增加多个键值对:OK
        System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));//获取多个键值对:[value01, value02, value03]
        System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03","key04"));//获取多个键值对:[value01, value02, value03, null]
        System.out.println("删除多个键值对:"+jedis.del("key01","key02"));//删除多个键值对:2
        System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));//获取多个键值对:[null, null, value03]

        jedis.flushDB();//清除当前数据库数据
        System.out.println("===========新增键值对防止覆盖原先值==============");
        //setnx [如果不存在,则增加键值对]
        System.out.println(jedis.setnx("key1", "value1"));//输出结果为1
        System.out.println(jedis.setnx("key2", "value2"));//输出结果为1
        System.out.println(jedis.setnx("key2", "value2-new"));//输出结果为0
        System.out.println(jedis.get("key1"));//value1
        System.out.println(jedis.get("key2"));//value2

        System.out.println("===========新增键值对并设置有效时间=============");
        System.out.println(jedis.setex("key3", 2, "value3"));//OK
        System.out.println(jedis.get("key3"));//value3
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(jedis.get("key3"));//null

        System.out.println("===========获取原值,更新为新值==========");
        System.out.println(jedis.getSet("key2", "key2GetSet"));//value2
        System.out.println(jedis.get("key2"));//key2GetSet

        System.out.println("获得key2的值的字串:"+jedis.getrange("key2", 2, 4));//获得key2的值的字串:y2G
    }
}

5.测试list

package com.demo.redis;

import redis.clients.jedis.Jedis;

/**
 * @className: TestList
 * @description: 测试list
 * @author: 
 * @create: 
 **/

public class TestList {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();
        System.out.println("===========添加一个list===========");
        jedis.lpush("list","a","b","c","d","e","f","g");//从头部添加
        jedis.lpush("list","h");
        jedis.lpush("list","i");
        jedis.lpush("list","j");
        jedis.rpush("list","x");//从尾部添加
        jedis.rpush("list","y");
        jedis.rpush("list","z");
        jedis.rpush("list","a");
        System.out.println("list的集合元素"+jedis.lrange("list",0,-1));//list的集合元素[j, i, h, g, f, e, d, c, b, a, x, y, z, a]
        System.out.println("list的集合中区间为0-3的元素"+jedis.lrange("list",0,3));//list的集合中区间为0-3的元素[j, i, h, g]
        System.out.println("===============================");
        // 删除列表指定的值 ,第二个参数为删除的个数(有重复时)
        System.out.println("删除指定元素个数:"+jedis.lrem("list",2,"a"));//删除指定元素个数:2
        System.out.println("list的集合元素"+jedis.lrange("list",0,-1));//list的集合元素[j, i, h, g, f, e, d, c, b, x, y, z]
        System.out.println("list列表出栈(左端):"+jedis.lpop("list"));//list列表出栈(左端):j
        System.out.println("list的集合元素"+jedis.lrange("list",0,-1));//list的集合元素[i, h, g, f, e, d, c, b, x, y, z]
        System.out.println("list列表初中(右端):"+jedis.rpop("list"));//list列表初中(右端):z
        System.out.println("list的集合元素"+jedis.lrange("list",0,-1));//list的集合元素[i, h, g, f, e, d, c, b, x, y]
        System.out.println("修改list集合指定下标为1的内容:"+jedis.lset("list", 1, "111"));//修改list集合指定下标为1的内容:OK
        System.out.println("list的集合元素"+jedis.lrange("list",0,-1));//list的集合元素[i, 111, g, f, e, d, c, b, x, y]
        System.out.println("===============================");
        System.out.println("list集合的长度:"+jedis.llen("list"));//list集合的长度:10
        System.out.println("获取list集合下标为2的元素:"+jedis.lindex("list", 2));//获取list集合下标为2的元素:g
        System.out.println("===============================");
        jedis.lpush("sortedList", "3","6","2","0","7","4");
        System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));//sortedList排序前:[4, 7, 0, 2, 6, 3]
        System.out.println("sortedList排序后:"+jedis.sort("sortedList"));//[0, 2, 3, 4, 6, 7]
        jedis.close();
    }
}

6.测试set

import redis.clients.jedis.Jedis;

/**
 * @className: TestSet
 * @description: 测试set
 * @author: 
 * @create: 
 **/

public class TestSet {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();
        System.out.println("============向集合中添加元素(无序不重复)============");
        System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));//8
        System.out.println(jedis.sadd("eleSet", "e6"));//1
        System.out.println(jedis.sadd("eleSet", "e6"));//0
        System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));//eleSet的所有元素为:[e5, e2, e8, e1, e4, e3, e6, e0, e7]
        System.out.println("删除一个元素e0:"+jedis.srem("eleSet", "e0"));//删除一个元素e0:1
        System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));//eleSet的所有元素为:[e8, e1, e4, e3, e6, e7, e2, e5]
        System.out.println("删除两个元素e7和e6:"+jedis.srem("eleSet", "e7","e6"));//删除两个元素e7和e6:2
        System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));//eleSet的所有元素为:[e3, e4, e1, e2, e5, e8]
        System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));//随机的移除集合中的一个元素:e8
        System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));//随机的移除集合中的一个元素:e3
        System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));//eleSet的所有元素为:[e4, e1, e2, e5]
        System.out.println("eleSet中包含元素的个数:"+jedis.scard("eleSet"));//eleSet中包含元素的个数:4
        System.out.println("e3是否在eleSet中:"+jedis.sismember("eleSet", "e3"));//e3是否在eleSet中:false
        System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e1"));//e1是否在eleSet中:true
        System.out.println("e5是否在eleSet中:"+jedis.sismember("eleSet", "e5"));//e5是否在eleSet中:true
        System.out.println("=================================");
        System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));//8
        System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));//6
        System.out.println("将eleSet1中删除e1并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e1"));//将eleSet1中删除e1并存入eleSet3中:1
        System.out.println("将eleSet1中删除e2并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e2"));//将eleSet1中删除e2并存入eleSet3中:1
        System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));//eleSet1中的元素:[e7, e3, e0, e5, e8, e4]
        System.out.println("eleSet3中的元素:"+jedis.smembers("eleSet3"));//eleSet3中的元素:[e2, e1]
        System.out.println("============集合运算=================");
        System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));//eleSet1中的元素:[e7, e3, e0, e5, e8, e4]
        System.out.println("eleSet2中的元素:"+jedis.smembers("eleSet2"));//eleSet2中的元素:[e2, e4, e1, e3, e0, e8]
        System.out.println("eleSet1和eleSet2的交集:"+jedis.sinter("eleSet1","eleSet2"));//eleSet1和eleSet2的交集:[e4, e3, e0, e8]
        System.out.println("eleSet1和eleSet2的并集:"+jedis.sunion("eleSet1","eleSet2"));//eleSet1和eleSet2的并集:[e8, e1, e4, e3, e0, e7, e5, e2]
        //eleSet1中有,eleSet2中没有
        System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2"));//eleSet1和eleSet2的差集:[e7, e5]
        jedis.sinterstore("eleSet4","eleSet1","eleSet2");//求交集并将交集保存到dstkey(eleSet4)的集合
        System.out.println("eleSet4中的元素:"+jedis.smembers("eleSet4"));//eleSet4中的元素:[e0, e3, e8, e4]
    }
}

7.测试hash

package com.demo.redis;

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * @className: TestHash
 * @description: 测试hash
 * @author: 
 * @create: 
 **/

public class TestHash {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();
        Map<String,String> map = new HashMap<String,String>();
        map.put("key1","value1");
        map.put("key2","value2");
        map.put("key3","value3");
        map.put("key4","value4");
        //添加名称为hash的所有元素
        jedis.hmset("hash",map);
        //向名称为hash的hash集合中添加key为key5,value为value5的元素
        jedis.hset("hash","key5","value5");
        System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));//散列hash的所有键值对为:{key1=value1, key2=value2, key5=value5, key3=value3, key4=value4}
        System.out.println("散列hash的所有键为:"+jedis.hkeys("hash"));//散列hash的所有键为:[key1, key2, key5, key3, key4]
        System.out.println("散列hash的所有值为:"+jedis.hvals("hash"));//散列hash的所有值为:[value1, value2, value3, value4, value5]
        System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("hash", "key6", 6));//将key6保存的值加上一个整数,如果key6不存在则添加key6:6
        System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));//散列hash的所有键值对为:{key1=value1, key2=value2, key5=value5, key6=6, key3=value3, key4=value4}
        System.out.println("删除一个或多个键值对:"+jedis.hdel("hash","key2"));//删除一个或多个键值对:1
        System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));//散列hash的所有键值对为:{key1=value1, key5=value5, key6=6, key3=value3, key4=value4}
        System.out.println("散列hash中键值对的个数:"+jedis.hlen("hash"));//散列hash中键值对的个数:5
        System.out.println("判断hash中是否存在key2:"+jedis.hexists("hash","key2"));//判断hash中是否存在key2:false
        System.out.println("判断hash中是否存在key3:"+jedis.hexists("hash","key3"));//判断hash中是否存在key3:true
        System.out.println("获取hash中的值:"+jedis.hmget("hash","key3"));//获取hash中的值:[value3]
        System.out.println("获取hash中的值:"+jedis.hmget("hash","key3","key4"));//获取hash中的值:[value3, value4]
    }
}

8.测试zset

package com.demo.redis;

import redis.clients.jedis.Jedis;

import java.util.HashMap;

import static jdk.nashorn.internal.objects.Global.Infinity;

/**
 * @className: TestZset
 * @description: 测试Zset
 * @author: 
 * @create: 
 **/

public class TestZset {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.zadd("myzset",100,"张三");
        jedis.zadd("myzset",200,"李四");
        jedis.zadd("myzset",300,"王五");
        System.out.println("查看Zset集合的所有元素:"+jedis.zrange("myzset",0, -1));
        HashMap<String, Double> map = new HashMap<String, Double>();
        map.put("赵六",400D);
        map.put("杨样",500d);
        //给myzsest集合添加多个元素
        jedis.zadd("myzset",map);
        System.out.println("查看Zset集合的所有元素:"+jedis.zrange("myzset",0, -1));
        jedis.flushDB();
        System.out.println("=================利用zset对集合元素进行排序=================");
        HashMap<String, Double> hashMap = new HashMap<String, Double>();
        hashMap.put("xiaoHong",7000d);
        hashMap.put("xiaoLi",5000d);
        hashMap.put("lily",4000d);
        hashMap.put("xiaoLan",10000d);
        jedis.zadd("money",hashMap);
        System.out.println("查看money集合的所有元素从小到大:"+jedis.zrange("money",0, -1));
        System.out.println("查看money集合的所有元素从大到小:"+jedis.zrevrange("money",0, -1));
        System.out.println("=================对集合元素的值进行从小到大排序=================");
        System.out.println(jedis.zrangeByScore("money",-Infinity,+Infinity));//[lily, xiaoLi, xiaoHong, xiaoLan]
        System.out.println(jedis.zrangeByScore("money",4000,+Infinity));//在4000到正无穷大 [lily, xiaoLi, xiaoHong, xiaoLan]
        System.out.println(jedis.zrangeByScore("money",0,+Infinity));//0-正无穷大 [lily, xiaoLi, xiaoHong, xiaoLan]
        System.out.println("=================对集合元素的值进行从大到小排序=================");
        System.out.println(jedis.zrevrangeByScore("money",+Infinity,-Infinity));//[xiaoLan, xiaoHong, xiaoLi, lily]
        System.out.println(jedis.zrevrangeByScore("money",5000,1000));//在1000-5000 [xiaoLi, lily]
        System.out.println(jedis.zrevrangeByScore("money",+Infinity,1000));//在1000-无穷大之间 [xiaoLan, xiaoHong, xiaoLi, lily]
        System.out.println("================移除元素=================");
        System.out.println("查看money集合的所有元素从小到大:"+jedis.zrange("money",0, -1));//查看money集合的所有元素从小到大:[lily, xiaoLi, xiaoHong, xiaoLan]
        System.out.println("从money集合中删除lily元素:"+jedis.zrem("money","lily"));//从money集合中删除lily元素:1
        System.out.println("查看money集合的所有元素从小到大:"+jedis.zrange("money",0, -1));//查看money集合的所有元素从小到大:[xiaoLi, xiaoHong, xiaoLan]
        System.out.println("从money集合中删除xiaoHong元素:"+jedis.zrem("money","xiaoHong"));//从money集合中删除xiaoHong元素:1
        System.out.println("查看money集合的所有元素从小到大:"+jedis.zrange("money",0, -1));//查看money集合的所有元素从小到大:[xiaoLi, xiaoLan]
        System.out.println("================获取有序集合中的个数=================");
        System.out.println("获取money集合中的个数:"+jedis.zcard("money"));//获取money集合中的个数:2
        System.out.println("================zcount 区间的成员数量================");
        HashMap<String, Double> countMap = new HashMap<String, Double>();
        countMap.put("a",1000d);
        countMap.put("b",1258d);
        countMap.put("c",2000d);
        countMap.put("d",5000d);
        countMap.put("e",10000d);
        System.out.println("给countMap集合添加多个元素:"+jedis.zadd("countMap",countMap));//给countMap集合添加多个元素:5
        System.out.println("查看countMap集合的所有元素从大到小:"+jedis.zrevrange("countMap",0, -1));//查看countMap集合的所有元素从大到小:[e, d, c, b, a]
        System.out.println("获取countMap集合中指定区间的成员数量:"+jedis.zcount("countMap",1000,+Infinity));//获取countMap集合中指定区间的成员数量:5
        System.out.println("获取countMap集合中指定区间的成员数量:"+jedis.zcount("countMap",4000,+Infinity));//获取countMap集合中指定区间的成员数量:2

    }
}

9.自定义RedisTemplate

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @className: RedisConfig
 * @description: 自定义RedisTemplate
 * @author:
 * @create:
 **/
@Configuration
public class RedisConfig {

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        // 为了自己开发方便,一般直接使用 
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        // Json序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // String 的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return  template;
    }
}

你可能感兴趣的:(java,java,API,redis,redisTemplate,nosql)