千家信息网

Redis的介绍及应用

发表于:2024-10-22 作者:千家信息网编辑
千家信息网最后更新 2024年10月22日,本篇内容主要讲解"Redis的介绍及应用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Redis的介绍及应用"吧!官网下不了,这里找了这个地址,版本比较老
千家信息网最后更新 2024年10月22日Redis的介绍及应用

本篇内容主要讲解"Redis的介绍及应用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Redis的介绍及应用"吧!

官网下不了,这里找了这个地址,版本比较老

下载驱动,搜索jedis

参考

基本操作

public class RedisTest {        public static void main(String[] args) {                        /**                 * 地址 端口 超时时间                 */                Jedis jedis = new Jedis("localhost", 6379, 100000);                /**                 * 测试是否通                  */                System.out.println("服务正在运行: "+jedis.ping());                                /**                  * set:设置key值                  * get:获取key值                  * del:删除key                  * append:追加key值                  * incr:key值自增1                  * incrBy:key值自增,指定步长                  * decr:key值自减1                  * decrBy:key值自减,指定步长                  * expire:为key设置过期时间(秒数)                  * setex:设置key值,可指定存活时间(秒数)                  * setnx:设置key值。key不存在才会设置,如果key存在则回滚操作,结果返回0,表示没有设置成功                  * ttl:time to live,获取key的存活时间(秒),-1表示永不过期                  * persist:去掉key的expire设置,不再有失效时间                  */                  jedis.set("first", "Hello World!");                System.out.println(jedis.get("first"));                                /**                  * LIST                 * 可以实现队列的功能                  * lpush: 从列表头部插入多个元素                  * rpush:从列表尾部插入多个元素                  * llen:返回列表中的元素的数量                  * lpop:从列表头部移除并返回list的第一个元素                  * lrem:从头部开始找,删除n个值                  * lrange:从列表中获取指定范围的子集                  */                jedis.del("list");                jedis.lpush("list", "1","2","3");                jedis.lpush("list", "4");                Long count=jedis.llen("list");                List list=jedis.lrange("list", 0, count);                System.out.println(list.toString());                                                /**                  * sadd:往set对象中添加一个值                  * smembers:取得set中所有的值                  * sismember:判断一个值是否在set中存在                  * srandmember:从set中随机取得一个值                  * srem:从set中删除一个值                  * scard:返回set的item个数                  */                jedis.del("set");                jedis.sadd("set", "1","2","3");                jedis.sadd("set", "4");                jedis.sadd("set", "4");                Set set=jedis.smembers("set");                System.out.println(set.toString());                                /**                  * hmset:设置key值,值类型为map对象                  * type:返回key值的类型,可能值有none, string, hash, set, list, zset                  * hkeys:获取所有key                  * hvals:获取所有key对应的值                  * hmget:一次性获取多个field的值                  * hexists:判断field是否存在                  * hset:设置field的值                  * hgetAll:获取全部内容                  * hget:获取field的值                  * hdel:删除field                  * hincrBy:field值自增1                  * hlen:计算field的数目                  * hsetnx:设置key值。field不存在才会设置,如果field存在则回滚操作,结果返回0,表示没有设置成功。可以用来实现分布式锁                  */                  jedis.del("user");                                    Map map = new HashMap();                      map.put("name", "cjm");                      map.put("age", "33");                      map.put("qq", "123456");                                            jedis.hmset("user", map);                      System.out.println("type: " + jedis.type("user"));                                             System.out.println("hkeys: " + jedis.hkeys("user"));                       System.out.println("hvals: " + jedis.hvals("user"));                                            System.out.println("hmget: " + jedis.hmget("user", "name", "age"));                       System.out.println("hexists: " + jedis.hexists("user", "name"));                                            jedis.hset("user", "pwd", "123");                       System.out.println("hgetAll: " + jedis.hgetAll("user"));                       System.out.println("hget: " + jedis.hget("user", "pwd"));                       jedis.hdel("user", "qq");                       System.out.println("hincrBy: " + jedis.hincrBy("user", "count", 1));                       System.out.println("hlen: " + jedis.hlen("user"));                                             Long r = jedis.hsetnx("user", "pwd2", "456");                       System.out.println(r);         }}

消息订阅、

订阅public class Consumer {        public static void main(String[] args) {                /**                 * 地址 端口 超时时间                 */                Jedis jedis = new Jedis("localhost", 6379, 100000);                 /**             * 消息订阅             */            JedisPubSub jps=new JedisPubSub() {                    public void onPMessage(String pattern, String channel, String message) {                            System.out.println("onPMessage()," + pattern + "=" + channel + "="                                            + message);                    }                                 public void onMessage(String channel, String message) {                            System.out.println("onMessage()," + channel + "=" + message);                    }            };                        jedis.psubscribe(jps, "test*");        }}//发布 jedis.publish("test1", "message from test1"); jedis.publish("test2", "message from test2");

redis分布式锁

public class RedisTool {    private static final String LOCK_SUCCESS = "OK";    private static final Long RELEASE_SUCCESS = 1L;        /**     * 尝试获取分布式锁     * @param jedis Redis客户端     * @param lockKey 锁     * @param requestId 请求标识     * @param expireTime 超期时间     * @return 是否获取成功     */    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {                String result = jedis.set(lockKey, requestId,new SetParams().nx().ex(expireTime));        if (LOCK_SUCCESS.equals(result)) {            return true;        }        return false;    }        /**     * 释放分布式锁     * @param jedis Redis客户端     * @param lockKey 锁     * @param requestId 请求标识     * @return 是否释放成功     */    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));        if (RELEASE_SUCCESS.equals(result)) {            return true;        }        return false;    }}public class LockTest {        public static void main(String[] args) {                Runnable rn = new Runnable() {                        @Override                        public void run() {                                Jedis jedis = new Jedis("localhost", 6379, 100000);                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");                                int tryCount=5;                                while (true) {                                        Boolean lock = RedisTool.tryGetDistributedLock(jedis, "lock", uuid, 10);                                        if (lock) {                                                System.out.println(Thread.currentThread().getName() + "获取锁");                                                try {                                                        Thread.sleep(1000L);                                                } catch (InterruptedException e) {                                                        e.printStackTrace();                                                }                                                Boolean unlock = RedisTool.releaseDistributedLock(jedis, "lock", uuid);                                                if (unlock) {                                                        System.out.println(Thread.currentThread().getName() + "释放锁");                                                        break;                                                }                                        }                                                                                if(tryCount<0) {                                                break;                                        }else {                                                try {                                                        Thread.sleep(2000);                                                } catch (InterruptedException e) {                                                        e.printStackTrace();                                                }                                                System.out.println(Thread.currentThread().getName() + "尝试次数:"+tryCount);                                                tryCount--;                                        }                                }                        }                };                for (int i = 0; i < 20; i++) {                        Thread t = new Thread(rn);                        t.start();                }                LockSupport.park();        }}

锁测试

package com.redis;import java.util.UUID;import java.util.concurrent.locks.LockSupport;import redis.clients.jedis.Jedis;public class ProductServer {        /**         * 向服务端添加货         *          * @return         */        public boolean addProduct(Jedis jedis, String key, int i) {                System.out.println("货物:" + key + "添加库存:" + i);                if (i > 0) {                        System.out.println("---添加货物:" + key + "数量:" + i + "---");                        // 获取值                        String count = jedis.get(key);                        System.out.println("剩余库存:" + count);                        if (null == count || Integer.valueOf(count) <= 0) {                                System.out.println("---当前货物:" + key + "数量已销售完毕");                                System.out.println("---当前货物:" + key + "添加开始");                                jedis.set(key, i + "");                                System.out.println("---当前货物:" + key + "添加结束");                                return true;                        }                }                return false;        }        /**         * 消费数据         */        public boolean decryProduct(Jedis jedis, String key, String requestID) {                try {                Boolean lock = RedisTool.tryGetDistributedLock(jedis, "lock", requestID, 100);                        if (!lock) {                                System.out.println("请稍后重试...");                                return false;                        }                        System.out.println("货物:" + key + "线程:" + Thread.currentThread().getName() + "消费数据:" + requestID);                        String count = jedis.get(key);                        if (null != count && Integer.valueOf(count) > 0) {                                jedis.decr(key);                                count = jedis.get(key);                                System.out.println("剩余库存:" + count);                                return true;                        }                } catch (Exception e) {                } finally {                        RedisTool.releaseDistributedLock(jedis, "lock", requestID);                }                return false;        }        public static void main(String[] args) {                Jedis jedis = new Jedis("localhost", 6379, 10000);                ProductServer ps = new ProductServer();                ps.addProduct(jedis, "shouji", 10);                Runnable rn = new Runnable() {                        @Override                        public void run() {                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");                                Jedis jedis = new Jedis("localhost", 6379, 10000);                                ps.decryProduct(jedis, "shouji", uuid);                        }                };                for (int i = 0; i < 15; i++) {                        Thread td = new Thread(rn);                        td.start();                }                LockSupport.park();        }}

到此,相信大家对"Redis的介绍及应用"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0