《Try Redis》笔记

本文深入探讨Redis作为高性能键值存储系统的特点,包括其支持的多种数据结构如字符串、列表、集合、有序集合等,以及原子操作和复杂数据结构处理方式。同时介绍了Redis在缓存、数据库和消息中间件领域的应用。
  • Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询

  • Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。

  • Redis支持

    (1) 基本类型: int, double…

    (2) 字符串

    (3) list

  • Redis__区分大小写__

    connection和CONNECTION是两个变量

  • redis-cli -h {host} -p {port}

    和主机名为host、端口号为port上的redis进行交互

  • Redis Command

      DECR
      
      DECRBY
      
      DEL
      
      EXISTS
      
      EXPIRE
      
      GET
      
      GETSET
      
      HDEL
      
      HEXISTS
      
      HGET
      
      HGETALL
      
      HINCRBY
      
      HKEYS
      
      HLEN
      
      HMGET
      
      HMSET
      
      HSET
      
      HVALS
      
      INCR
      
      INCRBY
      
      KEYS
      
      LINDEX
      
      LLEN
      
      LPOP
      
      LPUSH
      
      LRANGE
      
      LREM
      
      LSET
      
      LTRIM
      
      MGET
      
      MSET
      
      MSETNX
      
      MULTI
      
      PEXPIRE
      
      RENAME
      
      RENAMENX
      
      RPOP
      
      RPOPLPUSH
      
      RPUSH
      
      SADD
      
      SCARD
      
      SDIFF
      
      SDIFFSTORE
      
      SET
      
      SETEX
      
      SETNX
      
      SINTER
      
      SINTERSTORE
      
      SISMEMBER
      
      SMEMBERS
      
      SMOVE
      
      SORT
      
      SPOP
      
      SRANDMEMBER
      
      SREM
      
      SUNION
      
      SUNIONSTORE
      
      TTL
      
      TYPE
      
      ZADD
      
      ZCARD
      
      ZCOUNT
      
      ZINCRBY
      
      ZRANGE
      
      ZRANGEBYSCORE
      
      ZRANK
      
      ZREM
      
      ZREMRANGEBYSCORE
      
      ZREVRANGE
      
      ZSCORE
    
  • Redis is what is called a key-value store, often referred to as a NoSQL database. The essence of a key-value store is the ability to store some data, called a value, inside a key. This data can later be retrieved only if we know the exact key used to store it. We can use the command SET to store the value “fido” at key “server:name”:

      SET server:name "fido"
    

    Redis will store our data permanently, so we can later ask “What is the value stored at key server:name?” and Redis will reply with “fido”:

      GET server:name => "fido"
    

    Tip: You can click the commands above to automatically execute them. The text after the arrow (=>) shows the expected output.

  • Other common operations provided by key-value stores are DEL to delete a given key and associated value, SET-if-not-exists (called SETNX on Redis) that sets a key only if it does not already exist, and INCR to atomically increment a number stored at a given key:

      SET connections 10
      INCR connections => 11
      INCR connections => 12
      DEL connections
      INCR connections => 1
    
  • There is something special about INCR. Why do we provide such an operation if we can do it ourself with a bit of code? After all it is as simple as:

      x = GET count
      x = x + 1
      SET count x
    

    The problem is that doing the increment in this way will only work as long as there is a single client using the key. See what happens if two clients are accessing this key at the same time:

      Client A reads count as 10.
      Client B reads count as 10.
      Client A increments 10 and sets count to 11.
      Client B increments 10 and sets count to 11.
    

    We wanted the value to be 12, but instead it is 11! This is because incrementing the value in this way is not an atomic operation. Calling the INCR command in Redis will prevent this from happening, because it is an atomic operation.

    Redis provides many of these atomic operations on different types of data.

  • Redis can be told that a key should only exist for a certain length of time. This is accomplished with the EXPIRE and TTL commands.

      SET resource:lock "Redis Demo"
      EXPIRE resource:lock 120
    

    This causes the key resource:lock to be deleted in 120 seconds. You can test how long a key will exist with the TTL command. It returns the number of seconds until it will be deleted.

      TTL resource:lock => 113
      // after 113s
      TTL resource:lock => -2
    

    The -2 for the TTL of the key means that the key does not exist (anymore). A -1 for the TTL of the key means that it will never expire.

    Note that if you SET a key, its TTL will be reset.

      SET resource:lock "Redis Demo 1"
      EXPIRE resource:lock 120
      TTL resource:lock => 119
      SET resource:lock "Redis Demo 2"
      TTL resource:lock => -1
    
  • Redis also supports several more complex data structures. The first one we’ll look at is a list. A list is a series of ordered values. Some of the important commands for interacting with lists are RPUSH, LPUSH, LLEN, LRANGE, LPOP, and RPOP. You can immediately begin working with a key as a list, as long as it doesn’t already exist as a different type.

    (1) RPUSH puts the new value at the end of the list.

      RPUSH friends "Alice"
      RPUSH friends "Bob"
    

    (2) LPUSH puts the new value at the start of the list.

      LPUSH friends "Sam"
    

    (3) LRANGE gives a subset of the list. It takes the index of the first element you want to retrieve (begin with 0, inclusive) as its first parameter and the index of the last element you want to retrieve(inclusive) as its second parameter. A value of -1 for the second parameter means to retrieve elements until the end of the list.

      LRANGE friends 0 -1 => 1) "Sam", 2) "Alice", 3) "Bob"
      LRANGE friends 0 1 => 1) "Sam", 2) "Alice"
      LRANGE friends 1 2 => 1) "Alice", 2) "Bob"
    

    (4) LLEN returns the current length of the list.

      LLEN friends => 3
    

    (5) LPOP removes the first element from the list and returns it.

      LPOP friends => "Sam"
    

    (6) RPOP removes the last element from the list and returns it.

      RPOP friends => "Bob"
    

    Note that the list now only has one element:

      LLEN friends => 1
      LRANGE friends 0 -1 => 1) "Alice"
    
  • The next data structure that we’ll look at is a set. A set is similar to a list, except it does not have a specific order and each element may only appear once. Some of the important commands in working with sets are SADD, SREM, SISMEMBER, SMEMBERS and SUNION.

    (1) SADD adds the given value to the set.

      SADD superpowers "flight"
      SADD superpowers "x-ray vision"
      SADD superpowers "reflexes"
    

    (2) SREM removes the given value from the set.

      SREM superpowers "reflexes"
    

    (3) SISMEMBER tests if the given value is in the set. It returns 1 if the value is there and 0 if it is not.

      SISMEMBER superpowers "flight" => 1
      SISMEMBER superpowers "reflexes" => 0
    

    (4) SMEMBERS returns a list of all the members of this set.

      SMEMBERS superpowers => 1) "flight", 2) "x-ray vision"
    

    (5) SUNION combines two or more sets and returns the list of all elements (but never modify the two or more sets).

      SADD birdpowers "pecking"
      SADD birdpowers "flight"
      SUNION superpowers birdpowers => 1) "pecking", 2) "x-ray vision", 3) "flight"
    

    Sets are a very handy data type, but as they are unsorted they don’t work well for a number of problems

  • A sorted set is similar to a regular set, but now each value has an associated score. This score is used to sort the elements in the set.

      ZADD hackers 1940 "Alan Kay"
      ZADD hackers 1906 "Grace Hopper"
      ZADD hackers 1953 "Richard Stallman"
      ZADD hackers 1965 "Yukihiro Matsumoto"
      ZADD hackers 1916 "Claude Shannon"
      ZADD hackers 1969 "Linus Torvalds"
      ZADD hackers 1957 "Sophie Wilson"
      ZADD hackers 1912 "Alan Turing"
    

    In these examples, the scores are years of birth and the values are the names of famous hackers.

      ZRANGE hackers 2 4 => 1) "Claude Shannon", 2) "Alan Kay", 3) "Richard Stallman"
    
  • Simple strings, sets and sorted sets already get a lot done but there is one more data type Redis can handle: Hashes.

    (1) Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth):

      HSET user:1000 name "John Smith"
      HSET user:1000 email "john.smith@example.com"
      HSET user:1000 password "s3cret"
    

    (2) To get back the saved data use HGETALL:

      HGETALL user:1000
    

    (3) You can also set multiple fields at once use HMSET:

      HMSET user:1001 name "Mary Jones" password "hidden" email "mjones@example.com"
    

    (4) If you only need a single field value that is possible as well use HGET:

      HGET user:1001 name => "Mary Jones"
    

    (5) Numerical values in hash fields are handled exactly the same as in simple strings and there are operations to increment this value in an atomic way.

      HSET user:1000 visits 10
      HINCRBY user:1000 visits 1 => 11
      HINCRBY user:1000 visits 10 => 21
      HDEL user:1000 visits
      HINCRBY user:1000 visits 1 => 1
    
多源动态最优潮流的分布鲁棒优化方法(IEEE118节点)(Matlab代码实现)内容概要:本文介绍了基于Matlab代码实现的多源动态最优潮流的分布鲁棒优化方法,适用于IEEE118节点电力系统。该方法结合两阶段鲁棒模型与确定性模型,旨在应对电力系统中多源输入(如可再生能源)的不确定性,提升系统运行的安全性与经济性。文中详细阐述了分布鲁棒优化的建模思路,包括不确定性集合的构建、目标函数的设计以及约束条件的处理,并通过Matlab编程实现算法求解,提供了完整的仿真流程与结果分析。此外,文档还列举了大量相关电力系统优化研究案例,涵盖微电网调度、电动汽车集群并网、需求响应、储能配置等多个方向,展示了其在实际工程中的广泛应用价值。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的研究生、科研人员及从事能源系统优化工作的工程师。; 使用场景及目标:①用于研究高比例可再生能源接入背景下电力系统的动态最优潮流问题;②支撑科研工作中对分布鲁棒优化模型的复现与改进;③为电力系统调度、规划及运行决策提供理论支持与仿真工具。; 阅读建议:建议读者结合提供的Matlab代码与IEEE118节点系统参数进行实操演练,深入理解分布鲁棒优化的建模逻辑与求解过程,同时可参考文中提及的其他优化案例拓展研究思路。
### 关于 Redis 分布式的教程和笔记 #### 使用 Redisson 实现分布式锁 在 Redis 集群环境中,为了确保分布式系统的高可用性和一致性,推荐采用成熟的库如 Redisson 来实现分布式锁功能。Redisson 提供了一套简单易用的 API 接口用于操作 Redis,并内置支持多种数据结构以及高级特性比如分布式锁、队列等[^1]。 ```java // 创建 RedissonClient 对象实例化配置类 Config 并设置单节点地址连接池大小超时时间等参数 Config config = new Config(); config.useSingleServer().setAddress("redis://127.0.0.1:6379"); RLock lock = redisson.getLock("myDistributedLock"); try { // 加锁并指定最大等待时间和保持时间单位为秒 boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS); } finally { // 解锁释放资源 lock.unlock(); } ``` #### Redlock 协议的理解与应用 Antirez (即 Salvatore Sanfilippo),作为 Redis 的主要开发者之一,在其博客文章中提出了名为 "Redlock" 的算法来解决多个独立 Redis 实例间的一致性问题。该方案通过增加额外的安全措施防止脑裂现象发生从而提高整个集群环境下的可靠性[^2]。 #### CAP理论下Redis的选择考量 当涉及到构建分布式的存储系统时,CAP 定理是一个重要的指导原则。它指出任何网络分区容忍性的服务都无法同时提供强一致性和高度可利用性;因此设计者需要在这两者之间做出取舍。对于像 Redis 这样的内存数据库而言,通常会倾向于 AP 或 CP 方向发展取决于具体应用场景的需求[^3]。 #### 利用Lua脚本增强原子性保障 除了依靠第三方工具外还可以借助 Lua 脚本来加强自定义逻辑执行过程中的事务安全性。例如可以将加解锁动作封装成一段完整的命令序列交给服务器端一次性完成以此减少中间状态暴露的风险[^4]。 ```lua local key = KEYS[1] local value = ARGV[1] if(redis.call('exists',key)==0)then redis.call('setex',key,'10',value) else return nil; end return true; ``` #### Spring Boot 中集成 AOP 拦截器模式管理锁机制 最后值得一提的是现代 Java 应用程序开发框架往往提供了便捷的方式帮助程序员更好地控制业务流程走向。以 Spring Boot 为例可以通过创建切面组件围绕目标函数调用周期实施环绕通知进而达到自动获取/释放关联对象的目的[^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值