4-8 Redis

简介

  • redis是一个非关系型数据库(NoSQL),数据从内存中读取,快于数据从硬盘中读取,所以redis的数据查询效率高于mysql。
  1. redis是一个高性能的(key/value)分布式内存数据库;
  2. redis是一个NoSql数据库,基于内存运行也支持持久化;
  3. redis的持久化方案有两种:RDB和AOF
  • RDB 是 Redis 默认的持久化方案。在指定的时间间隔内,执行指定次数的写操作,则会将内存中的数据写入到磁盘中。即在指定目录下生成一个dump.rdb文件(快照)。Redis 重启会通过加载dump.rdb文件恢复数据。
  • AOF 在Redis中默认不开启。它的出现是为了弥补RDB的不足(数据的不一致性),所以它采用日志的形式来记录每个写操作,并追加到文件中。Redis 重启后会根据日志文件的内容将写指令从前到后执行一次以完成数据的恢复工作。

应用场景

  1. 高速缓存
  2. 分布式锁(乐观锁)

特点

  1. redis默认有16个库;
  2. redis是单线程的,最新版本的redis支持多线程的
  3. 支持数据库主从复制,主库master数据会同步到从库slave,同步策略有全量同步、增量同步;
  4. 分布式系统下,redis可以利用哨兵模式Sentinel监控主机工作状态,在Master主服务器发生故障的时候,可以实现Master和Slave服务器的切换,保证系统的高可用;
  5. 单个Redis命令的执行是原子性的,但 Redis没有在事务上增加任何维持原子性的机制(批量redis指令是非原子性的),所以 Redis 事务的执行并不是原子性的。

NoSQL产品

  1. redis
  2. mongoDB

常用指令

在这里插入图片描述

五种基本数据类型

String
  • 字符串
    在这里插入图片描述
Hash
  • Redis的hash 是一个 string 类型的 field 和 value 的映射表,field和value是字符串类型
  • 类似于java里面的Map<String, String>
    在这里插入图片描述
List
  • Redis列表是简单的字符串列表,按照插入顺序排序。
  • 可以添加一个元素到列表的头部(左边)或者尾部(右边)。
  • 底层实现是个链表,链表可以两端双向插入。
    在这里插入图片描述
Set
  • Redis 的 Set 是 String 类型的无序集合,集合成员是唯一的,Set集合中的元素无序且不可重复。
    在这里插入图片描述
Sorted Set
  • sorted set中的元素有序不可重复。有序集合的成员是唯一的,但分数(score)却可以重复。
  • Sorted Set和Set一样也是String 类型元素的集合,且不允许重复的成员。不同的是每个元素都会关联一个 double 类型的分数。redis 正是通过分数来为集合中的成员进行从小到大的排序。
    在这里插入图片描述

配置文件

  • maven pom.xml
<!-- redis -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- jedis: redis连接驱动-->
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>3.1.0</version>
</dependency>
  • application.yml
# redis数据源
redis:
  # redis服务ip地址
  host: 127.0.0.1
  # 服务端口号
  port: 6379
  # 密码
  password:
  database: 2
  pool:
    # 连接池最大连接数(负值表示没有限制)
    max-active: 8
    # 连接池最大阻塞等待时间(负值表示没有限制)
    max-wait: 1
    # 最大空闲连接
    max-idle: 8
    # 最小空闲连接
    min-idle: 0
  # 连接超时时间(毫秒)
  timeout: 30000
  # 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
  blockWhenExhausted: false

代码示例

Jedis

  • 配置类 RedisConfig.java
package com.st.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

//声明是配置类,且兼具@Component的作用
@Configuration
public class RedisConfig {
    @Value("${redis.host}") //读取yml配置文件,将配置文件中的值,赋值值变量
    private String host;

    @Value("${redis.port}")
    private int port;

    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.pool.max-idle}")
    private int maxIdle;

    @Value("${redis.pool.max-wait}")
    private int maxWaitMillis;

    @Value("${redis.blockWhenExhausted}")
    private Boolean blockWhenExhausted;

    @Value("${redis.password}")
    private String passWord;

    @Value("${redis.database}")
    private int dataBase;

    @Bean //将本方法返回的类对象,注入到ioc容器中去
    public JedisPool jedisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //加载连接池配置
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);

        // 是否启用pool的jmx监控,可用于监控资源使用状态 【默认值:true】
        //使用建议:开启
//        jedisPoolConfig.setJmxEnabled(JmxEnabled);
        //创建redis连接类
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, null, dataBase);

        return jedisPool;
    }
}
  • RedisUseDemo
package com.st.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/*
redis操作示例
 */
@Component
public class RedisUseDemo {

    @Autowired
    private JedisPool jedisPool;

    private Jedis jedis = null;

    public void connection(){
        if(jedis == null) {
            //建立redis连接
            jedis = jedisPool.getResource();
        }
    }

    /**
     * 向Redis中存值,永久有效
     */
    public String set(String key, String value) {
        connection();
        try {
            //添加键指对,如果key已经存在,覆盖原来的值,成功返回OK
            String res = jedis.set(key, value);

            //只有当key的值不存在时,设置key的值,成功返回1 失败返回0
//            long res = jedis.setnx(key, value);

            //设置过期时间,单位秒(s)
//            if ("ok".equals(res.toLowerCase())) jedis.expire(key, 60);
            System.out.println(res);
            return "OK";
        } catch (Exception e) {
            return "0";
        } finally {
            //关闭连接
            jedis.close();
        }
    }

    /**
     * 根据传入Key获取指定Value
     */
    public String get(String key) {
        connection();
        String value = null;
        try {
            value = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return value;
    }

    /**
     * 校验Key值是否存在
     */
    public Boolean exists(String key) {
        connection();
        try {
            return jedis.exists(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            jedis.close();
        }
    }

    /**
     * 删除指定Key-Value
     */
    public Long del(String key) {
        connection();
        try {
            return jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        } finally {
            jedis.close();
        }
    }

}
  • RedisController.java
package com.st.controller;
import com.st.config.RedisUseDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("redis")
public class RedisController {

    @Autowired
    private RedisUseDemo redis;

    @RequestMapping("/t")
    public String test(){
        return redis.set("name", "张三");
    }
}

RedisTemplate

  • @EnableCaching:开启Spring缓存
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    
    RedisSerializer<Object> serializer = RedisSerializer.json();
    
    // 使用StringRedisSerializer来序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(serializer);

    // Hash的key也采用StringRedisSerializer的序列化方式
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(serializer);

    template.afterPropertiesSet();
    return template;
}

SpringCache

  • @EnableCaching:开启Spring缓存
@Value("${spring.redis.default-ttl:300}")	// 默认取300
private long defaultTTL;					// 默认过期时间
/**
 * 配置 默认TTL和Redis缓存注解的value序列化方式
 */
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
    RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
    RedisSerializationContext.SerializationPair<Object> serializationPair = RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json());
    configuration = configuration
        .entryTtl(Duration.ofSeconds(defaultTTL))       // 默认过期时间
        .serializeValuesWith(serializationPair);    // 自定义序列化方式 json
    return configuration;
}
  • @Cacheable
@Cacheable(value = "redis1", key = "#root.methodName + ':fileName=' + #fileName")
@Override
public FileVo getFileVo(String fileName) {
    return new FileVo().setFileName(fileName);
}

方法所在类被以Spring Bean方式注入并实例化后,再通过实例对象调用该方法,@Cacheable的缓存功能才会触发。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值