微服务Redis解析部署使用全流程

目录

1、什么是Redis

2、Redis的作用

3、Redis常用的五种基本类型(重要知识点)

4、安装redis

4.1、查询镜像文件【省略】

4.2、拉取镜像文件

4.3、启动redis并设置密码

4.3.1、修改redis密码【可以不修改】

4.3.2、删除密码【坚决不推荐】

5、SpringBoot整合

1、在pom.xml文件中添加maven依赖

2、添加redis配置

3、添加redisconfig

4、添加SpringBoot启动类:

5、常用方法介绍(重要)

1.redisTemplate

2.ValueOperations=>String

3.HashOperations=>Hash

4.ListOperations=>List

5.SetOperations=>Set

6.ZSetOperations=>zSet

6.redis缓存穿透、缓存击穿、缓存雪崩区别和解决方案


1、什么是Redis

Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

可以理解成一个大容量的map。

2、Redis的作用

可以做为数据库存储数据,也可以用来做缓存、计数器、分布式锁等。实际工作中很少用它做数据库。

3、Redis常用的五种基本类型(重要知识点)

  • string:字符串数据类型

  • hash:类似于对象,map的形式

  • list:表示一种线性数据结构,队列或栈

  • set:无序不可重复集合

  • zset:有序不可重复集合

另外还有三种数据类型,都不是很常用。Geospatial、Bitmap、Hyperloglog

redis可以操作位(bit),但是工作中几乎不用。

4、安装redis

基于docker的安装

4.1、查询镜像文件【省略】

bash 复制代码
#可以不操作:
docker search redis

4.2、拉取镜像文件

docker pull redis:6.2.6

4.3、启动redis并设置密码

bash 复制代码
docker run -d --name redis-6379 -p 6379:6379 redis:6.2.6 --requirepass 123456

requirepass:设置密码

【工作时:】启动redis注意事项:

  • 密码一定要设置,复杂一点

  • 端口映射,redis一定不能用默认端口,用默认端口一定会被攻击

4.3.1、修改redis密码【可以不修改】

bash 复制代码
# 1/进入redis容器
docker exec -it redis-6379 /bin/bash
# 2/找到redis-cli可执行文件
cd /usr/local/bin
# 3/执行redis-cli
redis-cli
# 4/查看密码
config get requirepass
# 5/授权
auth 密码
# 6/修改密码
config set requirepass 新密码

第一步骤:进入redis容器

第二步骤:找到redis-cli可执行文件

第三步骤:执行redis-cli

第四步骤:查看密码(显示没有授权)

第五步骤:授权

第六步骤:修改密码(最好还是使用123456,后面整合的时候,容易忘记。)

第七步骤:退出容器

4.3.2、删除密码【坚决不推荐】

config set requirepass ''

5、SpringBoot整合

1、在pom.xml文件中添加maven依赖

XML 复制代码
<?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>

    <groupId>com.jr</groupId>
    <artifactId>redis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.13</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.6.13</spring-boot.version>
        <jwt.version>0.7.0</jwt.version>
        <fastjson.version>1.2.60</fastjson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
            <scope>compile</scope>
        </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>
                <configuration>
                    <classifier>exec</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、添加redis配置

XML 复制代码
#host:自身ip
spring:
  redis:
    host: 192.168.146.128    
    port: 6379
    password: 123456

3、添加redisconfig

java 复制代码
package com.jr.config;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    /**
     * 配置 RedisTemplate<String, Object>
     * 设置了键和值的序列化方式,键用字符串序列化,值用JSON序列化
     *
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        StringRedisSerializer keySerialize = new StringRedisSerializer();
        RedisTemplate<String, Object> result = new RedisTemplate<>();
        result.setConnectionFactory(redisConnectionFactory);
        result.setKeySerializer(keySerialize);
        result.setValueSerializer(valueSerializer);
        result.setHashKeySerializer(keySerialize);
        result.setHashValueSerializer(valueSerializer);
        return result;
    }

}

4、添加SpringBoot启动类:

java 复制代码
@SpringBootApplication
public class SpringBootMain {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMain.class);
    }
}

5、常用方法介绍(重要)

1.redisTemplate

redisTemplate.hasKey(key); //判断是否有key所对应的值,有则返回true,没有则返回false

redisTemplate.opsForValue().get(key); //有则取出key值所对应的值

redisTemplate.delete(key); //删除单个key值

redisTemplate.delete(keys); //其中keys:Collection<K> keys

redisTemplate.dump(key); //将当前传入的key值序列化为byte[]类型

redisTemplate.expire(key, timeout, unit); //设置过期时间

redisTemplate.expireAt(key, date); //设置过期时间

redisTemplate.keys(pattern); //查找匹配的key值,返回一个Set集合类型

redisTemplate.rename(oldKey, newKey); //返回传入key所存储的值的类型

redisTemplate.renameIfAbsent(oldKey, newKey); //如果旧值存在时,将旧值改为新值

redisTemplate.randomKey(); //从redis中随机取出一个key

redisTemplate.getExpire(key); //返回当前key所对应的剩余过期时间

redisTemplate.getExpire(key, unit); //返回剩余过期时间并且指定时间单位

redisTemplate.persist(key); //将key持久化保存

redisTemplate.move(key, dbIndex); //将当前数据库的key移动到指定redis中数据库当中

【测试代码】

java 复制代码
@Slf4j
@SpringBootTest(classes = DemoHelloworldApplication.class)
@SuppressWarnings("all")
public class RedisTest {

    private static final String KEY = "test:commonKey";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void testCommon() {
        testCommon(KEY);
    }

    public void testCommon(String key) {
        boolean hasKey = redisTemplate.hasKey(key); //hasKey(key);
        log.info("hasKey {}", hasKey);
        boolean delete = redisTemplate.delete(key); //delete(key);
        log.info("delete {}", delete);
    }

    public void delete(String key) {
        boolean delete = redisTemplate.delete(key);
    }
}  

2.ValueOperations=>String

ValueOperations opsForValue = redisTemplate.opsForValue();

opsForValue.set(key, value); //设置当前的key以及value值

opsForValue.set(key, value, offset);//用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始

opsForValue.set(key, value, timeout, unit); //设置当前的key以及value值并且设置过期时间

opsForValue.setBit(key, offset, value); //将二进制第offset位值变为value

opsForValue.setIfAbsent(key, value);//重新设置key对应的值,如果存在返回false,否则返回true

opsForValue.get(key, start, end); //返回key中字符串的子字符

opsForValue.getAndSet(key, value); //将旧的key设置为value,并且返回旧的key

opsForValue.multiGet(keys); //批量获取值

opsForValue.size(key); //获取字符串的长度

opsForValue.append(key, value); //在原有的值基础上新增字符串到末尾

opsForValue.increment(key,double increment);//以增量的方式将double值存储在变量中

opsForValue.increment(key,long increment); //通过increment(K key, long delta)方法以增量方式存储long值(正值则自增,负值则自减)

Map valueMap = new HashMap();

valueMap.put("valueMap1","map1");

valueMap.put("valueMap2","map2");

valueMap.put("valueMap3","map3");

opsForValue.multiSetIfAbsent(valueMap); //如果对应的map集合名称不存在,则添加否则不做修改

opsForValue.multiSet(valueMap); //设置map集合到redis

【测试代码】

java 复制代码
@Slf4j
@SpringBootTest(classes = DemoHelloworldApplication.class)
@SuppressWarnings("all")
public class RedisTest {

    private static final String KEY = "test:commonKey";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * - string:字符串数据类型
     */
    @Test
    public void testString() {
        String key = "test:string";
        String key2 = "test:increment";
        String key3 = "test:object";
        delete(key);
        delete(key2);
        delete(key3);
        redisTemplate.opsForValue().set(key, "zhangsan");  // set(key, "zhangsan");
        Object value = redisTemplate.opsForValue().get(key); // get(key);
        log.info("value {}", value);
        redisTemplate.opsForValue().set(key, "lisi");
        value = redisTemplate.opsForValue().get(key);
        log.info("value {}", value);
        testCommon(key);
        boolean hasKey = redisTemplate.hasKey(key);
        log.info("hasKey {}", hasKey);
        
        
        redisTemplate.opsForValue().increment(key2, 10);// increment(key2, 10);计数器
        value = redisTemplate.opsForValue().get(key2);
        log.info("value {}", value);
        redisTemplate.opsForValue().increment(key2); // increment(key2); 涨1;increment(key2,10);涨10
        value = redisTemplate.opsForValue().get(key2);
        log.info("value {}", value);
        
        
        User user = new User();
        user.setName("zhangsan");
        user.setPassword("123456");
        redisTemplate.opsForValue().set(key3, user);
        value = redisTemplate.opsForValue().get(key3);
        log.info("value {}", value);
    }
}    

3.HashOperations=>Hash

HashOperations opsForHash = redisTemplate.opsForHash();

opsForHash.get(key, field); //获取变量中的指定map键是否有值,如果存在该map键则获取值,没有则返回null

opsForHash.entries(key); //获取变量中的键值对

opsForHash.put(key, hashKey, value); //新增hashMap值

opsForHash.putAll(key, maps); //以map集合的形式添加键值对

opsForHash.putIfAbsent(key, hashKey, value); //仅当hashKey不存在时才设置

opsForHash.delete(key, fields); //删除一个或者多个hash表字段

opsForHash.hasKey(key, field); //查看hash表中指定字段是否存在

opsForHash.increment(key, field, long increment); //给哈希表key中的指定字段的整数值加上增量increment

opsForHash.increment(key, field, double increment); //给哈希表key中的指定字段的整数值加上增量increment

opsForHash.keys(key); //获取所有hash表中字段

opsForHash.values(key); //获取hash表中存在的所有的值

opsForHash.scan(key, options); //匹配获取键值对,ScanOptions.NONE为获取全部键对

【测试代码】

java 复制代码
@Slf4j
@SpringBootTest(classes = DemoHelloworldApplication.class)
@SuppressWarnings("all")
public class RedisTest {

    private static final String KEY = "test:commonKey";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * - hash:类似于对象,map的形式
     */
    @Test
    public void testHash() {
        String key = "test:hash";
        redisTemplate.opsForHash().put(key, "name", "zhangsan");
        redisTemplate.opsForHash().put(key, "age", 12);
        Object name = redisTemplate.opsForHash().get(key, "name");
        Object age = redisTemplate.opsForHash().get(key, "age");
        log.info("name {}", name);
        log.info("age {}", age);
    }
}  

4.ListOperations=>List

ListOperations opsForList = redisTemplate.opsForList();

opsForList.index(key, index); //通过索引获取列表中的元素

opsForList.range(key, start, end); //获取列表指定范围内的元素(start开始位置, 0是开始位置,end 结束位置, -1返回所有)

opsForList.leftPush(key, value); //存储在list的头部,即添加一个就把它放在最前面的索引处

opsForList.leftPush(key, pivot, value); //如果pivot处值存在则在pivot前面添加

opsForList.leftPushAll(key, value); //把多个值存入List中(value可以是多个值,也可以是一个Collection value)

opsForList.leftPushIfPresent(key, value); //List存在的时候再加入

opsForList.rightPush(key, value); //按照先进先出的顺序来添加(value可以是多个值,或者是Collection var2)

opsForList.rightPushAll(key, value); //在pivot元素的右边添加值

opsForList.set(key, index, value); //设置指定索引处元素的值

opsForList.trim(key, start, end); //将List列表进行剪裁

opsForList.size(key); //获取当前key的List列表长度

//移除并获取列表中第一个元素(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)

opsForList.leftPop(key);

opsForList.leftPop(key, timeout, unit);

//移除并获取列表最后一个元素

opsForList.rightPop(key);

opsForList.rightPop(key, timeout, unit);

//从一个队列的右边弹出一个元素并将这个元素放入另一个指定队列的最左边

opsForList.rightPopAndLeftPush(sourceKey, destinationKey);

opsForList.rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit);

//删除集合中值等于value的元素(index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素; index<0, 从尾部开始删除第一个值等于value的元素)

opsForList.remove(key, index, value);

【测试代码】

java 复制代码
@Slf4j
@SpringBootTest(classes = DemoHelloworldApplication.class)
@SuppressWarnings("all")
public class RedisTest {

    private static final String KEY = "test:commonKey";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * - list:表示一种线性数据结构,队列或栈
     */
    @Test
    public void testList() {
        String key = "test:list";
        
        log.info("----------------------- {}", "模拟队列");
        /*模拟队列*/
        for (int i = 0; i < 5; i++) {
            redisTemplate.opsForList().leftPush(key, i);
        }
        long listSize = redisTemplate.opsForList().size(key);
        log.info("listSize {}", listSize);
        for (int i = 0; i < listSize; i++) {
            log.info("test:list {}", redisTemplate.opsForList().rightPop(key));
        }
        listSize = redisTemplate.opsForList().size(key);
        log.info("listSize {}", listSize);
        
        
        log.info("----------------------- {}", "模拟栈");
        /*模拟栈*/
        for (int i = 0; i < 5; i++) {
            redisTemplate.opsForList().leftPush(key, i);
        }
        listSize = redisTemplate.opsForList().size(key);
        log.info("listSize {}", listSize);
        for (int i = 0; i < listSize; i++) {
            log.info("test:list {}", redisTemplate.opsForList().leftPop(key));
        }
        listSize = redisTemplate.opsForList().size(key);
        log.info("listSize {}", listSize);
        
    }
}   

5.SetOperations=>Set

SetOperations opsForSet = redisTemplate.opsForSet();

opsForSet.add(key, values); //添加元素

opsForSet.remove(key, values); //移除元素(单个值、多个值)

opsForSet.pop(key); //删除并且返回一个随机的元素

opsForSet.size(key); //获取集合的大小

opsForSet.isMember(key, value); //判断集合是否包含value

opsForSet.intersect(key, otherKey); //获取两个集合的交集(key对应的无序集合与otherKey对应的无序集合求交集)

opsForSet.intersect(key, otherKeys);//获取多个集合的交集(Collection var2)

opsForSet.intersectAndStore(key, otherKey, destKey); //key集合与otherKey集合的交集存储到destKey集合中(其中otherKey可以为单个值或者集合)

opsForSet.intersectAndStore(key, otherKeys, destKey); //key集合与多个集合的交集存储到destKey无序集合中

opsForSet.union(key, otherKeys); //获取两个或者多个集合的并集(otherKeys可以为单个值或者是集合)

opsForSet.unionAndStore(key, otherKey, destKey); //key集合与otherKey集合的并集存储到destKey中(otherKeys可以为单个值或者是集合)

opsForSet.difference(key, otherKeys); //获取两个或者多个集合的差集(otherKeys可以为单个值或者是集合)

opsForSet.differenceAndStore(key, otherKey, destKey); //差集存储到destKey中(otherKeys可以为单个值或者集合)

opsForSet.randomMember(key); //随机获取集合中的一个元素

opsForSet.members(key); //获取集合中的所有元素

opsForSet.randomMembers(key, count); //随机获取集合中count个元素

opsForSet.distinctRandomMembers(key, count); //获取多个key无序集合中的元素(去重),count表示个数

opsForSet.scan(key, options); //遍历set类似于Interator(ScanOptions.NONE为显示所有的)

【测试代码】

java 复制代码
@Slf4j
@SpringBootTest(classes = DemoHelloworldApplication.class)
@SuppressWarnings("all")
public class RedisTest {

    private static final String KEY = "test:commonKey";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * - set:无序不可重复集合
     */
    @Test
    public void testSet() {
        String key = "test:set";
        redisTemplate.opsForSet().add(key, "zhangsan", "lisi", "wangwu", 12, 22, 32, "wangwu", 12, "12");
        long listSize = redisTemplate.opsForSet().size(key);
        log.info("listSize {}", listSize);
        for (int i = 0; i < listSize; i++) {
            log.info("test:set {}", redisTemplate.opsForSet().pop(key));
        }
        listSize = redisTemplate.opsForSet().size(key);
        log.info("listSize {}", listSize);
    }
}    

6.ZSetOperations=>zSet

ZSetOperations提供了一系列方法对有序集合进行操作

ZSetOperations opsForZSet = redisTemplate.opsForZSet();

opsForZSet.add(key, value, score); //添加元素(有序集合是按照元素的score值由小到大进行排列)

opsForZSet.remove(key, values); //删除对应的value,value可以为多个值

opsForZSet.incrementScore(key, value, delta); //增加元素的score值,并返回增加后的值

opsForZSet.rank(key, value); //返回元素在集合的排名,有序集合是按照元素的score值由小到大排列

opsForZSet.reverseRank(key, value); //返回元素在集合的排名,按元素的score值由大到小排列

opsForZSet.reverseRangeWithScores(key, start,end); //获取集合中给定区间的元素(start 开始位置,end 结束位置, -1查询所有)

opsForZSet.reverseRangeByScore(key, min, max); //按照Score值查询集合中的元素,结果从小到大排序

opsForZSet.reverseRangeByScoreWithScores(key, min, max); //返回值为:Set<ZSetOperations.TypedTuple<V>>

opsForZSet.count(key, min, max); //根据score值获取集合元素数量

opsForZSet.size(key); //获取集合的大小

opsForZSet.zCard(key); //获取集合的大小

opsForZSet.score(key, value); //获取集合中key、value元素对应的score值

opsForZSet.removeRange(key, start, end); //移除指定索引位置处的成员

opsForZSet.removeRangeByScore(key, min, max); //移除指定score范围的集合成员

opsForZSet.unionAndStore(key, otherKey, destKey);//获取key和otherKey的并集并存储在destKey中(其中otherKeys可以为单个字符串或者字符串集合)

opsForZSet.intersectAndStore(key, otherKey, destKey); //获取key和otherKey的交集并存储在destKey中(其中otherKeys可以为单个字符串或者字符串集合)

【测试代码】

java 复制代码
@Slf4j
@SpringBootTest(classes = DemoHelloworldApplication.class)
@SuppressWarnings("all")
public class RedisTest {

    private static final String KEY = "test:commonKey";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * - zset:有序不可重复集合
     */
    @Test
    public void testZset() {
        String key = "test:zset";
        redisTemplate.opsForZSet().add(key, "zhangsan", 12);
        redisTemplate.opsForZSet().add(key, "lisi", 22);
        redisTemplate.opsForZSet().add(key, "wangwu", 32);
        redisTemplate.opsForZSet().add(key, "wangwu1", 121);
        redisTemplate.opsForZSet().add(key, "wangwu2", 122);
        redisTemplate.opsForZSet().add(key, "wangwu3", 123);
        redisTemplate.opsForZSet().add(key, "wangwu4", 124);
        redisTemplate.opsForZSet().add(key, "wangwu5", 125);
        redisTemplate.opsForZSet().add(key, "wangwu6", 126);
        Long zCard = redisTemplate.opsForZSet().zCard(key);//
        long listSize = redisTemplate.opsForZSet().size(key);
        log.info("zCard {}", zCard);
        log.info("listSize {}", listSize);
//        for (int i = 0; i < listSize; i++) {
//            log.info("test:set {}", redisTemplate.opsForZSet().popMax(key));
//        }
        listSize = redisTemplate.opsForZSet().size(key);
        log.info("listSize {}", listSize);
        log.info("----------------------- {}", "华丽的分割线");
        Set<Object> range = redisTemplate.opsForZSet().range(key, 1, 3);
        for (Object o : range) {
            log.info("range {}", o);
        }
        listSize = redisTemplate.opsForZSet().size(key);
        log.info("listSize {}", listSize);
    }
}

6.redis缓存穿透、缓存击穿、缓存雪崩区别和解决方案

https://blog.csdn.net/m0_71240584/article/details/142527527?spm=1001.2014.3001.5502

相关推荐
customer0812 分钟前
【开源免费】基于SpringBoot+Vue.JS服装销售平台(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·开源·intellij-idea
AutoAutoJack1 小时前
C# 事件(Event)应用说明二
开发语言·数据结构·算法·架构·c#
一颗知足的心1 小时前
SpringCloud Alibaba五大组件之——RocketMQ
spring·spring cloud·rocketmq
浅水壁虎1 小时前
SpringCloud第六章(服务保护CircuitBreaker) -2024
spring boot·spring·spring cloud
Yan-D2 小时前
【Redis 源码】2项目结构说明
数据库·redis·缓存
DieSnowK2 小时前
[Redis][事务]详细讲解
数据库·redis·缓存·事务·redis事务·新手向·事务操作
丁总学Java2 小时前
在 Docker 中进入 Redis 容器后,可以通过以下方法查看 Redis 版本:
redis·docker·容器
花千树-0103 小时前
深度对比:etcd、Consul、Zookeeper 和 Nacos 作为注册中心和配置中心的优势与劣势
微服务·zookeeper·服务发现·etcd·consul
点燃银河尽头的篝火(●'◡'●)3 小时前
【BurpSuite】SQL注入 | SQL injection(1-2)
数据库·redis·sql·网络安全
高高要努力3 小时前
SpringCloud-Netflix第一代微服务快速入门
spring·spring cloud·微服务