Redis基础教程:从入门到精通

发表时间: 2023-01-02 17:15
        1.基于内存的key-value数据库        2.基于c语言编写的,可以支持多种语言的api //set每秒11万次,取get 810003.支持数据持久化        4.value可以是stringhashlistset, sorted set        使用场景        1. 去最新n个数据的操作        2. 排行榜,取top n个数据 //最佳人气前103. 精确的设置过期时间        4. 计数器        5. 实时系统, 反垃圾系统        6. pub, sub发布订阅构建实时消息系统        7. 构建消息队列        8. 缓存        cmd访问redis        redis-cli.exe -h 127.0.0.1 -p 6379        key        keys * 获取所有的key        select 0 选择第一个库        move myString 1 将当前的数据库key移动到某个数据库,目标库有,则不能移动        flush db      清除指定库        randomkey     随机key        type key      类型        set key1 value1 设置key        get key1    获取key        mset key1 value1 key2 value2 key3 value3        mget key1 key2 key3        del key1   删除key        exists key      判断是否存在key        expire key 10   10过期        pexpire key 1000 毫秒        persist key     删除过期时间        string        set name cxx        get name        getrange name 0 -1        字符串分段        getset name new_cxx       设置值,返回旧值        mset key1 key2            批量设置        mget key1 key2            批量获取        setnx key value           不存在就插入(not exists)        setex key time value      过期时间(expire)        setrange key index valueindex开始替换value        incr age        递增        incrby age 10   递增        decr age        递减        decrby age 10   递减        incrbyfloat     增减浮点数        append          追加        strlen          长度        getbit/setbit/bitcount/bitop    位操作        hash        hset myhash name cxx        hget myhash name        hmset myhash name cxx age 25 note "i am notes"        hmget myhash name age note        hgetall myhash               获取所有的        hexists myhash name          是否存在        hsetnx myhash score 100      设置不存在的        hincrby myhash id 1          递增        hdel myhash name             删除        hkeys myhash                 只取key        hvals myhash                 只取value        hlen myhash                  长度        list        lpush mylist a b c  左插入        rpush mylist x y z  右插入        lrange mylist 0 -1  数据集合        lpop mylist  弹出元素        rpop mylist  弹出元素        llen mylist  长度        lrem mylist count value  删除        lindex mylist 2          指定索引的值        lset mylist 2 n          索引设值        ltrim mylist 0 4         删除key        linsert mylist before a  插入        linsert mylist after a   插入        rpoplpush list list2     转移列表的数据        set        sadd myset redis        smembers myset       数据集合        srem myset set1         删除        sismember myset set1 判断元素是否在集合中        scard key_name       个数        sdiff | sinter | sunion 操作:集合间运算:差集 | 交集 | 并集        srandmember          随机获取集合中的元素        spop                 从集合中弹出一个元素        zset        zadd zset 1 one        zadd zset 2 two        zadd zset 3 three        zincrby zset 1 one              增长分数        zscore zset two                 获取分数        zrange zset 0 -1 withscores     范围值        zrangebyscore zset 10 25 withscores 指定范围的值        zrangebyscore zset 10 25 withscores limit 1 2 分页        Zrevrangebyscore zset 10 25 withscores  指定范围的值        zcard zset  元素数量        Zcount zset 获得指定分数范围内的元素个数        Zrem zset one two        删除一个或多个元素        Zremrangebyrank zset 0 1  按照排名范围删除元素        Zremrangebyscore zset 0 1 按照分数范围删除元素        Zrank zset 0 -1    分数最小的元素排名为0        Zrevrank zset 0 -1  分数最大的元素排名为0        Zinterstore        zunionstore rank:last_week 7 rank:20150323 rank:20150324 rank:20150325  weights 1 1 1 1 1 1 1        排序:        sort mylist  排序        sort mylist alpha desc limit 0 2 字母排序        sort list by it:* desc           by命令        sort list by it:* desc get it:*  get参数        sort list by it:* desc get it:* store sorc:result  sort命令之store参数:表示把sort查询的结果集保存起来        订阅与发布:        订阅频道:subscribe chat1        发布消息:publish chat1 "hell0 ni hao"        查看频道:pubsub channels        查看某个频道的订阅者数量: pubsub numsub chat1        退订指定频道: unsubscrible chat1   , punsubscribe java.*        订阅一组频道: psubscribe java.*        redis事物:        隔离性,原子性,        步骤:  开始事务,执行命令,提交事务        multi  //开启事务        sadd myset a b c        sadd myset e f g        lpush mylist aa bb cc        lpush mylist dd ff gg        服务器管理        dump.rdb        appendonly.aof        //BgRewriteAof 异步执行一个aop(appendOnly file)文件重写        会创建当前一个AOF文件体积的优化版本        //BgSave 后台异步保存数据到磁盘,会在当前目录下创建文件dump.rdb        //save同步保存数据到磁盘,会阻塞主进程,别的客户端无法连接        //client kill 关闭客户端连接        //client list 列出所有的客户端        //给客户端设置一个名称        client setname myclient1        client getname        config get port        //configRewrite 对redis的配置文件进行改写        rdb save 900 1save 300 10save 60 10000        aop备份处理appendonly yes    开启持久化appendfsync everysec  每秒备份一次        命令:bgsave异步保存数据到磁盘(快照保存)lastsave返回上次成功保存到磁盘的unix的时间戳shutdown同步保存到服务器并关闭redis服务器bgrewriteaof文件压缩处理(命令)


使用Jedis操作Redis

package com.itheima.test;import org.junit.Test;import redis.clients.jedis.Jedi;import java.util.Set;/** * 使用Jedis操作Redis */public class JedisTest {    @Test    public void testRedis(){        //1 获取连接        Jedis jedis = new Jedis("localhost",6379);                //2 执行具体的操作        jedis.set("username","xiaoming");        String value = jedis.get("username");        System.out.println(value);        //jedis.del("username");        jedis.hset("myhash","addr","bj");        String hValue = jedis.hget("myhash", "addr");        System.out.println(hValue);        Set<String> keys = jedis.keys("*");        for (String key : keys) {            System.out.println(key);        }        //3 关闭连接        jedis.close();    }}

spring data redis




select + 数字(0.15),redis默认提供了16个数据库,在conf中可更改数据库数量



springboot使用Redis

pom文件

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.4.5</version>        <relativePath/>    </parent>    <groupId>com.itheima</groupId>    <artifactId>springdataredis_demo</artifactId>    <version>1.0-SNAPSHOT</version>    <properties>        <java.version>1.8</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>                <version>2.4.5</version>            </plugin>        </plugins>    </build></project>

yml文件

spring:  application:    name: springdataredis_demo  #Redis相关配置  redis:    host: localhost    port: 6379    #password: 123456    database: 0 #操作的是0号数据库    jedis:      #Redis连接池配置      pool:        max-active: 8 #最大连接数        max-wait: 1ms #连接池最大阻塞等待时间        max-idle: 4 #连接池中的最大空闲连接        min-idle: 0 #连接池中的最小空闲连接

redis config文件

package com.itheima.config;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.context.annotation.Bean;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.StringRedisSerializer;/** * Redis配置类 */@Configurationpublic class RedisConfig extends CachingConfigurerSupport {    @Bean    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();        //默认的Key序列化器为:JdkSerializationRedisSerializer        redisTemplate.setKeySerializer(new StringRedisSerializer());        redisTemplate.setHashKeySerializer(new StringRedisSerializer());        redisTemplate.setConnectionFactory(connectionFactory);        return redisTemplate;    }}

单元测试test

package com.itheima.test;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.redis.connection.DataType;import org.springframework.data.redis.core.*;import org.springframework.test.context.junit4.SpringRunner;import java.util.List;import java.util.Set;import java.util.concurrent.TimeUnit;@SpringBootTest@RunWith(SpringRunner.class)public class SpringDataRedisTest {    @Autowired    private RedisTemplate redisTemplate;    /**     * 操作String类型数据     */    @Test    public void testString(){        redisTemplate.opsForValue().set("city123","beijing");        String value = (String) redisTemplate.opsForValue().get("city123");        System.out.println(value);        redisTemplate.opsForValue().set("key1","value1",10l, TimeUnit.SECONDS);        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city1234", "nanjing");        System.out.println(aBoolean);    }    /**     * 操作Hash类型数据     */    @Test    public void testHash(){        HashOperations hashOperations = redisTemplate.opsForHash();        //存值        hashOperations.put("002","name","xiaoming");        hashOperations.put("002","age","20");        hashOperations.put("002","address","bj");        //取值        String age = (String) hashOperations.get("002", "age");        System.out.println(age);        //获得hash结构中的所有字段        Set keys = hashOperations.keys("002");        for (Object key : keys) {            System.out.println(key);        }        //获得hash结构中的所有值        List values = hashOperations.values("002");        for (Object value : values) {            System.out.println(value);        }    }    /**     * 操作List类型的数据     */    @Test    public void testList(){        ListOperations listOperations = redisTemplate.opsForList();        //存值        listOperations.leftPush("mylist","a");        listOperations.leftPushAll("mylist","b","c","d");        //取值        List<String> mylist = listOperations.range("mylist", 0, -1);        for (String value : mylist) {            System.out.println(value);        }        //获得列表长度 llen        Long size = listOperations.size("mylist");        int lSize = size.intValue();        for (int i = 0; i < lSize; i++) {            //出队列            String element = (String) listOperations.rightPop("mylist");            System.out.println(element);        }    }    /**     * 操作Set类型的数据     */    @Test    public void testSet(){        SetOperations setOperations = redisTemplate.opsForSet();        //存值        setOperations.add("myset","a","b","c","a");        //取值        Set<String> myset = setOperations.members("myset");        for (String o : myset) {            System.out.println(o);        }        //删除成员        setOperations.remove("myset","a","b");        //取值        myset = setOperations.members("myset");        for (String o : myset) {            System.out.println(o);        }    }    /**     * 操作ZSet类型的数据     */    @Test    public void testZset(){        ZSetOperations zSetOperations = redisTemplate.opsForZSet();        //存值        zSetOperations.add("myZset","a",10.0);        zSetOperations.add("myZset","b",11.0);        zSetOperations.add("myZset","c",12.0);        zSetOperations.add("myZset","a",13.0);        //取值        Set<String> myZset = zSetOperations.range("myZset", 0, -1);        for (String s : myZset) {            System.out.println(s);        }        //修改分数        zSetOperations.incrementScore("myZset","b",20.0);        //取值        myZset = zSetOperations.range("myZset", 0, -1);        for (String s : myZset) {            System.out.println(s);        }        //删除成员        zSetOperations.remove("myZset","a","b");        //取值        myZset = zSetOperations.range("myZset", 0, -1);        for (String s : myZset) {            System.out.println(s);        }    }    /**     * 通用操作,针对不同的数据类型都可以操作     */    @Test    public void testCommon(){        //获取Redis中所有的key        Set<String> keys = redisTemplate.keys("*");        for (String key : keys) {            System.out.println(key);        }        //判断某个key是否存在        Boolean itcast = redisTemplate.hasKey("itcast");        System.out.println(itcast);        //删除指定key        redisTemplate.delete("myZset");        //获取指定key对应的value的数据类型        DataType dataType = redisTemplate.type("myset");        System.out.println(dataType.name());    }}

查看spring自动配置



使用springcache

springcache使用redis缓存数据

1.导入maven坐标

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-cache</artifactId></dependency>

2.配置application.yml

spring:  redis:    host: 127.0.0.1    port: 6379    password:    database: 0  cache:    redis:      time-to-live: 1800000

3.启动类加注解@EnableCaching

package com.itheima.reggie;import lombok.extern.slf4j.Slf4j;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;import org.springframework.cache.annotation.EnableCaching;import org.springframework.transaction.annotation.EnableTransactionManagement;@Slf4j//@SpringBootApplication(scanBasePackages={"com.itheima.reggie"})@SpringBootApplication@ServletComponentScan@EnableTransactionManagement@EnableCachingpublic class ReggieApplication {    public static void main(String[] args) {        SpringApplication.run(ReggieApplication.class,args);        log.info("项目启动成功...");    }}

4.在controller方法加入注解@CacheEvict、@Cacheable

/**

* Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中

* value:缓存的名称,每个缓存名称下面可以有多个key

* key:缓存的key

* condition:条件,满足条件时才缓存数据 #result!=null

* unless:满足条件则不缓存

#p0是第一个参数

#user指的是参数对象

"#root.args[0]指的是第一个参数

//@CacheEvict(value = "userCache",key = "#p0.id")

//@CacheEvict(value = "userCache",key = "#user.id")

//@CacheEvict(value = "userCache",key = "#root.args[0].id")

*/

@PostMapping@CacheEvict(value = "setmealCache",allEntries = true)public R<String> save(@RequestBody SetmealDto setmealDto){    log.info("套餐信息:{}",setmealDto);    setmealService.saveWithDish(setmealDto);    return R.success("新增套餐成功");}


@GetMapping("/list")@Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")public R<List<Setmeal>> list(Setmeal setmeal) {    log.info("setmeal:{}", setmeal);    //条件构造器    LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();    queryWrapper.like(StringUtils.isNotEmpty(setmeal.getName()), Setmeal::getName, setmeal.getName());    queryWrapper.eq(null != setmeal.getCategoryId(), Setmeal::getCategoryId, setmeal.getCategoryId());    queryWrapper.eq(null != setmeal.getStatus(), Setmeal::getStatus, setmeal.getStatus());    queryWrapper.orderByDesc(Setmeal::getUpdateTime);    return R.success(setmealService.list(queryWrapper));}
@DeleteMapping@CacheEvict(value = "setmealCache",allEntries = true)public R<String> delete(@RequestParam List<Long> ids){    log.info("ids:{}",ids);    setmealService.removeWithDish(ids);    return R.success("套餐数据删除成功");}
package com.itheima.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.itheima.entity.User;import com.itheima.service.UserService;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.CachePut;import org.springframework.cache.annotation.Cacheable;import org.springframework.web.bind.annotation.*;import java.util.ArrayList;import java.util.List;@RestController@RequestMapping("/user")@Slf4jpublic class UserController {    @Autowired    private CacheManager cacheManager;    @Autowired    private UserService userService;    /**     * CachePut:将方法返回值放入缓存     * value:缓存的名称,每个缓存名称下面可以有多个key     * key:缓存的key     */    @CachePut(value = "userCache",key = "#user.id")    @PostMapping    public User save(User user){        userService.save(user);        return user;    }    /**     * CacheEvict:清理指定缓存     * value:缓存的名称,每个缓存名称下面可以有多个key     * key:缓存的key     */    @CacheEvict(value = "userCache",key = "#p0")    //@CacheEvict(value = "userCache",key = "#root.args[0]")    //@CacheEvict(value = "userCache",key = "#id")    @DeleteMapping("/{id}")    public void delete(@PathVariable Long id){        userService.removeById(id);    }    //@CacheEvict(value = "userCache",key = "#p0.id")    //@CacheEvict(value = "userCache",key = "#user.id")    //@CacheEvict(value = "userCache",key = "#root.args[0].id")    @CacheEvict(value = "userCache",key = "#result.id")    @PutMapping    public User update(User user){        userService.updateById(user);        return user;    }    /**     * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中     * value:缓存的名称,每个缓存名称下面可以有多个key     * key:缓存的key     * condition:条件,满足条件时才缓存数据 #result!=null     * unless:满足条件则不缓存     */    @Cacheable(value = "userCache",key = "#id",unless = "#result == null")    @GetMapping("/{id}")    public User getById(@PathVariable Long id){        User user = userService.getById(id);        return user;    }    @Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")    @GetMapping("/list")    public List<User> list(User user){        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();        queryWrapper.eq(user.getId() != null,User::getId,user.getId());        queryWrapper.eq(user.getName() != null,User::getName,user.getName());        List<User> list = userService.list(queryWrapper);        return list;    }}