Redis、Jedis及SpringDataRedis 快速入门

Redis


概念: redis是一款高性能的NOSQL系列的非关系型数据库

下载安装

命令操作

  • redis的数据结构

redis存储的是:key,value格式的数据,其中key都是字符串,value有5种不同的数据结构
* value的数据结构:
1) 字符串类型 string
2) 哈希类型 hash : map格式
3) 列表类型 list : linkedlist格式。支持重复元素
4) 集合类型 set : 不允许重复元素
5) 有序集合类型 sortedset:不允许重复元素,且元素有顺序在这里插入代码片

  • 字符串类型 string
  1. 存储: set key value
    127.0.0.1:6379> set username zhangsan
    OK
    2. 获取: get key
    127.0.0.1:6379> get username
    “zhangsan”
    3. 删除: del key
    127.0.0.1:6379> del age
    (integer) 1
  • 哈希类型 hash
  1. 存储:

hset key field value
127.0.0.1:6379> hset myhash username lisi
(integer) 1
127.0.0.1:6379> hset myhash password 123
(integer) 1

  1. 获取:

hget key field: 获取指定的field对应的值
127.0.0.1:6379> hget myhash username
“lisi”
hgetall key:获取所有的field和value
127.0.0.1:6379> hgetall myhash
1) “username”
2) “lisi”
3) “password”
4) “123”

  1. 删除:

hdel key field
127.0.0.1:6379> hdel myhash username
(integer) 1

  1. 列表类型list:

可以添加一个元素到列表的头部(左边)或者尾部(右边)

  • 添加:
  1. lpush key value: 将元素加入列表左表
  2. rpush key value:将元素加入列表右边
    127.0.0.1:6379> lpush myList a
    (integer) 1
    127.0.0.1:6379> lpush myList b
    (integer) 2
    127.0.0.1:6379> rpush myList c
    (integer) 3
  • 获取

lrange key start end :范围获取
127.0.0.1:6379> lrange myList 0 -1
1) “b”
2) “a”
3) “c”

  • 删除

lpop key: 删除列表最左边的元素,并将元素返回
rpop key: 删除列表最右边的元素,并将元素返回

  1. 集合类型set

不允许重复元素
1. 存储:sadd key value
127.0.0.1:6379> sadd myset a
(integer) 1
127.0.0.1:6379> sadd myset a
(integer) 0
2. 获取:smembers key:获取set集合中所有元素
127.0.0.1:6379> smembers myset
1) “a”
3. 删除:srem key value:删除set集合中的某个元素
127.0.0.1:6379> srem myset a
(integer) 1

  1. 有序集合类型sortedset

不允许重复元素,且元素有顺序.每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。

  • 存储

zadd key score value
127.0.0.1:6379> zadd mysort 60 zhangsan
(integer) 1
127.0.0.1:6379> zadd mysort 50 lisi
(integer) 1
127.0.0.1:6379> zadd mysort 80 wangwu
(integer) 1

  • 获取

zrange key start end [withscores]
127.0.0.1:6379> zrange mysort 0 -1
1) “lisi”
2) “zhangsan”
3) “wangwu”
127.0.0.1:6379> zrange mysort 0 -1 withscores
1) “zhangsan”
2) “60”
3) “wangwu”
4) “80”
5) “lisi”
6) “500”

  • 删除

zrem key value
127.0.0.1:6379> zrem mysort lisi
(integer) 1

  1. 通用命令
  1. keys * : 查询所有的键
  2. type key : 获取键对应的value的类型
  3. del key:删除指定的key value

持久化

  1. 概念

redis是一个内存数据库,当redis服务器重启,获取电脑重启,数据会丢失,我们可以将redis内存中的数据持久化保存到硬盘的文件中。

2.redis持久化机制

  1. RDB:默认方式,不需要进行配置,默认就使用这种机制
    * 在一定的间隔时间中,检测key的变化情况,然后持久化数据
    1. 编辑redis.windwos.conf文件
    # after 900 sec (15 min) if at least 1 key changed
    save 900 1
    # after 300 sec (5 min) if at least 10 keys changed
    save 300 10
    # after 60 sec if at least 10000 keys changed
    save 60 10000
    2. 重新启动redis服务器,并指定配置文件名称
    D:\redis\windows-64\redis-2.8.9>redis-server.exe redis.windows.conf
  1. AOF:日志记录的方式,可以记录每一条命令的操作。可以每一次命令操作后,持久化数据
    1. 编辑redis.windwos.conf文件
    appendonly no(关闭aof) --> appendonly yes (开启aof)
    # appendfsync always : 每一次操作都进行持久化
    appendfsync everysec : 每隔一秒进行一次持久化
    # appendfsync no : 不进行持久化

#Jedis

一款java操作redis数据库的工具

  • 使用步骤
  1. 下载jedis的jar包
  2. 使用
    //1. 获取连接
    Jedis jedis = new Jedis(“localhost”,6379);
    //2. 操作
    jedis.set(“username”,“zhangsan”);
    //3. 关闭连接
    jedis.close();
  • Jedis 操作各种redis中的数据结构
    1)字符串类型 String

    //1. 获取连接
    Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口
    //2. 操作
    //存储
    jedis.set(“username”,“zhangsan”);
    //获取
    String username = jedis.get(“username”);
    System.out.println(username);
    //可以使用setex()方法存储可以指定过期时间的 key value
    jedis.setex(“activecode”,20,“hehe”);//将activecode:hehe键值对存入redis,并且20秒后自动删除该键值对
    //3. 关闭连接
    jedis.close();

    1. 哈希类型 hash : map格式

    hset
    hget
    hgetAll
    //1. 获取连接
    Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口
    //2. 操作
    // 存储hash
    jedis.hset(“user”,“name”,“lisi”);
    jedis.hset(“user”,“age”,“23”);
    jedis.hset(“user”,“gender”,“female”);
    // 获取hash
    String name = jedis.hget(“user”, “name”);
    System.out.println(name);
    // 获取hash的所有map中的数据
    Map<String, String> user = jedis.hgetAll(“user”);
    // keyset
    Set keySet = user.keySet();
    for (String key : keySet) {
    //获取value
    String value = user.get(key);
    System.out.println(key + “:” + value);
    }
    //3. 关闭连接
    jedis.close();

    1. 列表类型 list : linkedlist格式。支持重复元素

    lpush / rpush
    lpop / rpop
    lrange start end : 范围获取
    //1. 获取连接
    Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口
    //2. 操作
    // list 存储
    jedis.lpush(“mylist”,“a”,“b”,“c”);//从左边存
    jedis.rpush(“mylist”,“a”,“b”,“c”);//从右边存
    // list 范围获取
    List mylist = jedis.lrange(“mylist”, 0, -1);
    System.out.println(mylist);
    // list 弹出
    String element1 = jedis.lpop(“mylist”);//c
    System.out.println(element1);
    String element2 = jedis.rpop(“mylist”);//c
    System.out.println(element2);
    // list 范围获取
    List mylist2 = jedis.lrange(“mylist”, 0, -1);
    System.out.println(mylist2);
    //3. 关闭连接
    jedis.close();

    1. 集合类型 set : 不允许重复元素

    sadd
    smembers:获取所有元素
    //1. 获取连接
    Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口
    //2. 操作
    // set 存储
    jedis.sadd(“myset”,“java”,“php”,“c++”);
    // set 获取
    Set myset = jedis.smembers(“myset”);
    System.out.println(myset);
    //3. 关闭连接
    jedis.close();

    1. 有序集合类型 sortedset:不允许重复元素,且元素有顺序

    zadd
    zrange
    //1. 获取连接
    Jedis jedis = new Jedis();//如果使用空参构造,默认值 “localhost”,6379端口
    //2. 操作
    // sortedset 存储
    jedis.zadd(“mysortedset”,3,“亚瑟”);
    jedis.zadd(“mysortedset”,30,“后裔”);
    jedis.zadd(“mysortedset”,55,“孙悟空”);
    // sortedset 获取
    Set mysortedset = jedis.zrange(“mysortedset”, 0, -1);
    System.out.println(mysortedset);
    //3. 关闭连接
    jedis.close();

  • jedis连接池

    • 使用
    1. 创建JedisPool连接池对象
    2. 调用方法 getResource()方法获取Jedis连接
      //0.创建一个配置对象
      JedisPoolConfig config = new JedisPoolConfig();
      config.setMaxTotal(50);
      config.setMaxIdle(10);
      //1.创建Jedis连接池对象
      JedisPool jedisPool = new JedisPool(config,“localhost”,6379);
      //2.获取连接
      Jedis jedis = jedisPool.getResource();
      //3. 使用
      jedis.set(“hehe”,“heihei”);
      //4. 关闭 归还到连接池中
      jedis.close();
    • 连接池工具类
        public class JedisPoolUtils {
    		    private static JedisPool jedisPool;			
    		    static{
    		        //读取配置文件
    		        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
    		        //创建Properties对象
    		        Properties pro = new Properties();
    		        //关联文件
    		        try {
    		            pro.load(is);
    		        } catch (IOException e) {
    		            e.printStackTrace();
    		        }
    		        //获取数据,设置到JedisPoolConfig中
    		        JedisPoolConfig config = new JedisPoolConfig();
    		        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
    		        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));	
    		        //初始化JedisPool
    		        jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
                    }
                     /**
    		     * 获取连接方法
    		     */
    		    public static Jedis getJedis(){
    		        return jedisPool.getResource();
    		    }
    		}
    

SrpingDataRedis配置

SpringDataRedis简介

SpringDataRedis 属于Spring Data 家族一员,用于对redis的操作进行封装的框架Spring Data ----- Spring 的一个子项目。Spring 官方提供一套数据层综合解决方案,用于简化数据库访问,支持NoSQL和关系数据库存储。包括Spring Data JPA 、SpringData Redis 、SpringDataSolr 、SpringDataElasticsearch 、Spring DataMongodb 等框架。

SpringDataRedis快速入门

  1. 准备工作
  • 构建Maven工程 SpringDataRedisDemo 引入Spring相关依赖、JUnit依赖、Jedis
    和SpringDataRedis依赖
    <!‐‐缓存‐‐>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring‐data‐redis</artifactId>
        <version>2.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring‐test</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
  • 在src/main/resources下创建properties文件夹,建立redis-config.properties
redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000

maxIdle :最大空闲数
maxWaitMillis: 连接时的最大等待毫秒数

  • 在src/main/resources下创建spring文件夹,创建applicationContext-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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath*:redis-config.properties"></context:property-placeholder>
    <!--redis相关配置-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
    </bean>
    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.host}"
        p:port="${redis.port}"
        p:password="${redis.pass}"
        p:poolConfig-ref="poolConfig"
    />
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
       <property name="connectionFactory" ref="JedisConnectionFactory"/>
   </bean>
</beans>
  1. 值类型操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext‐redis.xml")
public class TestValue {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("itcast");
    } 
    @Test
    public void getValue(){
        String str = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(str);
    } 
    @Test
    public void deleteValue(){
        redisTemplate.delete("name");;
    }
}
  1. Set类型操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext‐redis.xml")
public class TestSet {
@Autowired
private RedisTemplate redisTemplate;
    /**
    * 存入值
    */
    @Test
    public void setValue(){
        redisTemplate.boundSetOps("nameset").add("曹操");
        redisTemplate.boundSetOps("nameset").add("刘备");
        redisTemplate.boundSetOps("nameset").add("孙权");
    } /
    **
    * 提取值
    */
    @Test
    public void getValue(){
        Set members = redisTemplate.boundSetOps("nameset").members();
        System.out.println(members);
    } /
    **
    * 删除集合中的某一个值
    */
    @Test
    public void deleteValue(){
        redisTemplate.boundSetOps("nameset").remove("孙权");
    } /
    **
    * 删除整个集合
    */
    @Test
    public void deleteAllValue(){
        redisTemplate.delete("nameset");
    }
}
  1. List类型操作

    1. 右压栈 后添加的对象排在后边
  /**
    * 右压栈:后添加的对象排在后边
    */
    @Test
    public void testSetValue1(){
        redisTemplate.boundListOps("namelist1").rightPush("刘备");
        redisTemplate.boundListOps("namelist1").rightPush("关羽");
        redisTemplate.boundListOps("namelist1").rightPush("张飞");
    } /
    **
    * 显示右压栈集合
    */
    @Test
    public void testGetValue1(){
        List list = redisTemplate.boundListOps("namelist1").range(0, 10);
        System.out.println(list);
    }
2) 左压栈 后添加的对象排在前边
    /**
    * 左压栈:后添加的对象排在前边
    */
    @Test
    public void testSetValue2(){
        redisTemplate.boundListOps("namelist2").leftPush("刘备");
        redisTemplate.boundListOps("namelist2").leftPush("关羽");
        redisTemplate.boundListOps("namelist2").leftPush("张飞");   
    } /
    **
    * 显示左压栈集合
    */
    @Test
    public void testGetValue2(){
        List list = redisTemplate.boundListOps("namelist2").range(0, 10);
        System.out.println(list);
    }
3) 根据索引查询元素
/
**
* 查询集合某个元素
*/
    @Test
    public void testSearchByIndex(){
        String s = (String)
        redisTemplate.boundListOps("namelist1").index(1);
        System.out.println(s);
    }

4)移除指定个数的值
   /**
    * 移除集合某个元素
    */
    @Test
    public void testRemoveByIndex(){
        redisTemplate.boundListOps("namelist1").remove(1, "关羽");
    }
  1. Hash类型操作
    1. 存入值
    @Test
    public void testSetValue(){
        redisTemplate.boundHashOps("namehash").put("a", "唐僧");
        redisTemplate.boundHashOps("namehash").put("b", "悟空");
        redisTemplate.boundHashOps("namehash").put("c", "八戒");
        redisTemplate.boundHashOps("namehash").put("d", "沙僧");
    }
2) 提取所有的KEY
    @Test
    public void testGetKeys(){
        Set s = redisTemplate.boundHashOps("namehash").keys();
        System.out.println(s);  
    }
3) 提取所有的值
    @Test
    public void testGetValues(){
        List values = redisTemplate.boundHashOps("namehash").values();
        System.out.println(values);
    }
4) 根据KEY提取值
    @Test
    public void testGetValueByKey(){
        Object object = redisTemplate.boundHashOps("namehash").get("b");
        System.out.println(object); 
    }
5) 根据KEY移除值
    @Test
    public void testDeleteValueByKey(){
        redisTemplate.boundHashOps("namehash").delete("c");
    }
  1. ZSet类型操作
    1)存值 ,指定分值
    @Test
    public void setValue(){
        redisTemplate.boundZSetOps("namezset").add("曹操",100000);
        redisTemplate.boundZSetOps("namezset").add("孙权",0);
        redisTemplate.boundZSetOps("namezset").add("刘备",1000);    
    }
2)查询,由低到高
    /**
    * 由低到高排序
    */
    @Test
    public void getValue(){
        Set namezset = redisTemplate.boundZSetOps("namezset").range(0,1);
        System.out.println(namezset);   
    }
3)查询,由高到低,土豪榜前10
    /
    **
    * 由高到底排序(土豪榜)
    */
    @Test
    public void tuhaobang(){
        Set namezset = redisTemplate.boundZSetOps("namezset").reverseRange(0,9);
        System.out.println(namezset);
    }
4)增加分数
    /
    **
    * 增加分值
    */
    @Test
    public void addScore(){
        redisTemplate.boundZSetOps("namezset").incrementScore("孙权",2000);
    }
5)查询值和分数
   /**
    * 查询值和分数
    */
    @Test
    public void getValueAndScore(){
        Set<ZSetOperations.TypedTuple> namezset = redisTemplate.boundZSetOps("namezset").reverseRangeWithScores(0,1);
        //TypedTuple是值与分数的封装
        for(ZSetOperations.TypedTuple typedTuple:namezset){
            System.out.print("姓名:"+typedTuple.getValue());
            System.out.println("金币:"+typedTuple.getScore());
        }
    }
    
  1. 过期时间设置
  • 以值类型为例:存值时指定过期时间和时间单位
   /**
    * 存值
    */
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("itcast");
        redisTemplate.boundValueOps("name").expire(10,TimeUnit.SECONDS);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值