当前位置: 首页 > article >正文

Redis 基础、字符串、哈希、有序集合、集合、列表以及与 Jedis 操作 Redis 和与 Spring 集成。

目录

1. 数据类型

1.1 字符串

1.2 hash

1.3 List

1.4 Set

1.5 sorted set

2. jedis操作redis

3. 与spring集成


1. 数据类型

1.1 字符串

String是最常用的数据格式,普通的kay-value都归结为此类, value值不仅可以是string,可以是数字。
使用场景:通过用户的访问次数为依据封锁ip,可以将用户的访问次数已string类型记录在redis中,并通过
INCRBY操作,每次访问进行递增。
常用命令:
get, set, incr, decr, mget

示例:

​
# set
set name  zhangsan

# get
get name

#查看redis所有key
keys *

#查看redis中以name开发的key
keys name*

#设置一个数字
set num 1

#自增
incr num

#递减
decr num

​

1.2 hash

使用场景: 例如用户包含id,name,addr等属性,当需要使用redis存放用户信息时,可以使用hash。(和java中的Map很像)
常用命令: hget,hset,hgetall等

示例:

 # 以user:001为键,hash中有两个属性name为zs,age为19
 hset user:001 name zs age 19
 
 #获取以user:001为键,属性age的值
 hget user:001 age
 
 # 获取键为user:001的所用属性值
 hgetall user:001

1.3 List

应用场景:最新消息排行; 消息队列。利用Lists的push的操作,将任务存储在list中,然后工作线程再用pop操作将任务取出进行执行。

常用命令:
lpush,rpush,lpop,rpop,lrange,BLPOP(阻塞版)等

示例:

# 向队列中push数据
lpush bills zs li wu zl

#从队列中弹出数据,弹出后队列中的数据不保存
lpop bills

#队列的长度
llen bills

1.4 Set

常用场景: set与list比较类似,特殊之处是set可以自动排重,同时set还提供了某个成员是否存在于一个set内的接口,这个在list也没有。
常用命令:
sadd,srem,spop,sdiff ,smembers,sunion 等

示例:

# 向集合aa中加入1 2 3 4 5
sadd aa 1 2 3 4 5

# 向集合bb中加入4 5 6 7 8
sadd bb 4 5 6 7 8

# 返回集合aa中的所有元素
smembers aa

# 判断集合aa中是否存在元素1  ,存在返回1,不存在返回0
sismember aa 1

#返回aa集合中存在但bb中不存在的元素,返回 1 2 3 (差集)
sdiff aa bb

#求aa和bb集合的差集,并将结果保存到cc中去
sdiffstore cc aa bb

#求aa和bb的交集
sinter aa bb

#求aa和bb的交集,并将其存放到dd集合中去
sinterstore dd aa bb

#求aa和bb的并集
sunion aa bb

#求aa和bb的并集,将将其结果存放如ee集合
sunionstore ee aa bb

# 从ee集合中弹出3个元素(随机),默认弹出1个元素
spop ee 3

1.5 sorted set

使用场景:zset的使用场景与set类似,区别是set不是有序的,而zset可以通过用户额外提供的一个优先级(score即分值)参数来为成员排序,插入后自动排序。例如:将所有评论按发表时间为score存储,可以方便获取最新发表的评论;全班同学成绩的SortedSets,value可以是同学的学号,而score就可以是其考试得分,这样数据插入集合的,就已经进行了天然的排序。
另外还可以用Sorted Sets来做带权重的队列,比如普通消息的score为1,重要消息的score为2,然后工作线程可以选择按score的倒序来获取工作任务。让重要的任务优先执行。

常用命令:
zadd,zrange,zrem,zcard,zcount等

示例:

#将zs, ww, ls加入有序集合,其中zs 分值为1, ww 分值为2, ls分值为3
zadd zaa 1 zs 2 ww 3 ls

#获取zaa集合中score值从1到2范围内的元素
zrangebyscore zaa 1 2

#获取有序集合的成员数
zcard zaa

#计算在有序集合中指定区间分数的成员数
zcount zaa 1 2
#判断key在redis中是否存在。
exists key

2. jedis操作redis

1)创建一个maven工程
File ->New -> maven project -> create a simple project,输入maven坐标。

2) 在pom.xml文件中加jedis依赖

      <dependencies>
            <dependency>
                  <groupId>redis.clients</groupId>
                  <artifactId>jedis</artifactId>
                  <version>2.9.0</version>
            </dependency>
      </dependencies>

3)在pom.xml中指定jdk版本

<build>
    <finalName>填写自己的项目名称</finalName>
    <plugins>
          <!--第一步就是配置maven-compiler-plugin插件 -->
          <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                      <encoding>UTF-8</encoding>
                </configuration>
          </plugin>
    </plugins>
</build>

3)示例代码


//创建Jedis实例,连接redis
Jedis jedis = new Jedis("192.168.62.133",6379);

//ping,如果成功返回 pong
String rv = jedis.ping();
System.out.println(rv);

//string
jedis.set("name", "zs");

//hash
jedis.hset("user", "name", "张三");
jedis.hset("user", "age", "20");
jedis.hset("user", "tele", "12344344343");
jedis.hset("user", "addr", "长沙");

Map<String,String> user = new HashMap<>();
user.put("name", "李四");
user.put("age", "23");
user.put("tele", "23897989");
user.put("addr", "成都");
jedis.hmset("user02", user);

//list
jedis.lpush("list", "a");
jedis.lpush("list", "b");
jedis.lpush("list", "c");
jedis.lpush("list", "d");

System.out.println(jedis.rpop("list"));
System.out.println(jedis.rpop("list"));
System.out.println(jedis.rpop("list"));
System.out.println(jedis.rpop("list"));

//set
jedis.sadd("set", "aa","bb","cc");
System.out.println(jedis.spop("set"));
System.out.println(jedis.spop("set"));
System.out.println(jedis.spop("set"));

//sortset
Map<String,Double> zz = new HashMap<>();
zz.put("zz", 0.1D);
jedis.zadd("zset", zz);

Map<String,Double> ff = new HashMap<>();
ff.put("ff", 0.2D);
jedis.zadd("zset", ff);

Map<String,Double> qq = new HashMap<>();
qq.put("qq", 0.3D);
jedis.zadd("zset", qq);

System.out.println(jedis.zrangeByScore("zset", 0.1, 0.2));

//命令返回有序集中,指定区间内的成员, 其中成员的位置按分数值递减(从大到小)来排列
System.out.println(jedis.zrevrange("zset", 0, -1));

3. 与spring集成

1) 在pom.xml文件中导入依赖的包


<properties>
    <!-- redis版本 -->
    <redis.version>2.9.0</redis.version>
    <spring.redis.version>2.0.10.RELEASE</spring.redis.version>
    <spring.version>5.0.1.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
          <version>${redis.version}</version>
    </dependency>

    <!--2. spring相关(5.0.1.RELEASE) -->
    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
    </dependency>

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>${spring.version}</version>
    </dependency>

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
    </dependency>

    <!-- aop -->
    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
    </dependency>

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
    </dependency>

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
          <version>${spring.version}</version>
    </dependency>

    <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>1.6.11</version>
    </dependency>
    
    <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.11</version>
    </dependency>

    <dependency>
          <groupId>cglib</groupId>
          <artifactId>cglib</artifactId>
          <version>2.1_3</version>
    </dependency>

    <!--spring redis 支持-->
    <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-redis</artifactId>
         <version>1.7.2.RELEASE</version>
    </dependency>
    <!-- end -->
    
    <!--当将对象在redis中存储为json时需要-->
    <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.1.0</version>
    </dependency>

    <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.1.0</version>
    </dependency>

    <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.1.0</version>
    </dependency>

    <!--测试-->
    <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
    </dependency>

</dependencies>

2)spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"

      xmlns:context="http://www.springframework.org/schema/context" 
xmlns:tx="http://www.springframework.org/schema/tx"

      xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                    http://www.springframework.org/schema/beans/spring-beans.xsd
                          http://www.springframework.org/schema/aop 
                                    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                          http://www.springframework.org/schema/context 
                                    http://www.springframework.org/schema/context/spring-context-4.3.xsd
                          http://www.springframework.org/schema/tx 
                                    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">          

      <context:component-scan base-package="com.zking"/>

    <!-- 连接池基本参数配置,类似数据库连接池 -->
    <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true" />
   

    <!--redis连接池 -->  
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxActive}" />
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <!-- 连接池配置,类似数据库连接池 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">     
        <property name="hostName" value="${redis.host}"></property>
        <property name="port" value="${redis.port}"></property>
        <!-- <property name="password" value="${redis.pass}"></property> -->
        <property name="poolConfig" ref="poolConfig"></property>
    </bean>


    <!--redis操作模版,使用该对象可以操作<u>redis</u>  -->  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
        <property name="connectionFactory" ref="jedisConnectionFactory"/>   

        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->    
        <property name="keySerializer" >    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
        </property>    
        <property name="valueSerializer" >    
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> 
        </property>    
        <property name="hashKeySerializer">    
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>    
        <property name="hashValueSerializer">    
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>   
        </property>    
        <!--开启事务  -->  
        <property name="enableTransactionSupport" value="true">
        </property>  
    </bean >

</beans>

3) 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:spring*.xml")
@SuppressWarnings("all")
public class TestRedis {

      @Autowired
      private RedisTemplate<String, Object> redisTemplate;
      
      @Test
      public void testRedis() {
            redisTemplate.opsForHash().put("myhash", "name", "xiaoxiao");
            redisTemplate.opsForHash().put("myhash", "age", "12");
            redisTemplate.opsForHash().put("myhash", "addr", "changsha");
      
            Map<Object, Object> entries = redisTemplate.opsForHash().entries("myhash");

            for(Map.Entry e: entries.entrySet()) {
                  System.out.println(e.getKey());
                  System.out.println(e.getValue());
            }
      }
}

测试类通过则说明集成完成(请确定redis可正常访问)


http://www.kler.cn/news/149898.html

相关文章:

  • 【备忘录】快速回忆ElasticSearch的CRUD
  • Linux: Ftrace: function_graph 里面有irq处理的函数
  • Linux使用固定ip地址
  • Linux MYSQL-5.7.23-rpm安装(附带安装包)
  • 基于深度学习的点云三维目标检测方法综述
  • 算法基础之KMP算法
  • PHP连接数据库 错误抑制 三元运算符 学习资料
  • 解决PDF预览时,电子签章、日期等不显示问题
  • 基于springboot实现农机电招平台系统项目【项目源码+论文说明】计算机毕业设计
  • einj 注入内存ue/ce故障
  • 人工智能_机器学习055_拉格朗日乘子法_拉格朗日乘数法的原理介绍_流程详解---人工智能工作笔记0095
  • 团购生鲜系统丨分销丨外卖丨跑腿丨app小程序H5,源码交付,支持二开!
  • 轻松整合Knife4j:快速搭建Swagger文档界面与接口调试
  • 面试题背诵,回答的思路和模板,思路清晰
  • 【论文笔记】SDCL: Self-Distillation Contrastive Learning for Chinese Spell Checking
  • 基于LangChain实现的知识库问答工具Langchain-Chatchat
  • 数据库的增删查改(CRUD)基础版
  • C++面试的一些总结day1:指针和引用的区别
  • Spring Boot 在进行依赖注入时,使用了反射机制,类加载器-启动类拓展类-应用类加载器
  • 第二十章Java博客
  • Java学习笔记45——类的加载和反射机制
  • Android 13 - Media框架(14)- OpenMax(三)
  • 新王加冕,GPT-4V 屠榜视觉问答
  • Python---练习:求某同学成绩的总分及平均分
  • 二分查找(折半查找)探究学习
  • 常见的 QML 类型
  • MySQL之JDBC编程
  • 阿里巴巴矢量图标库的使用
  • calendar --- 日历相关函数
  • C++中的前缀和