SpringBoot_redis使用实战(一)_docker环境

6 篇文章 0 订阅
3 篇文章 0 订阅


前言

从实战docker安装redis, 到springboot项目中redis的综合使用.由浅入深

一 redis简单安装[docker]

传送门:centos7.4安装docker

1. 拉取镜像

[root@localhost ~]# docker pull redis:latest

2. 启动容器

docker run -itd --name redis_01 -p 6379:6379 redis --requirepass 123456

当然也可以不设置密码

docker run -itd --name redis_01 -p 6379:6379 redis

启动参数简单说明

  • -d redis 表示后台启动redis
  • -p 6379:6379 端口映射:前表示主机部分,:后表示容器部分。
  • –name redis_01 指定该容器名称,查看和进行操作都比较方便。

3. 命令行操作

进入容器,打开redis-cli客户端, 里面进行各种测试

[root@localhost ~]# docker exec -it redis_01 /bin/bash
root@bdb73e0f4414:/data# redis-cli -p 6379 -a 123456
127.0.0.1:6379> key *

停止redis

docker stop redis_01

移除容器

docker rm redis_01

二 springboot 集成redis

1. maven依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.18.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
		<!-- redis-lettuce连接池依赖 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>
    </dependencies>

2. application.properties

spring:
  redis:
    # Redis服务器主机地址
    host: 192.168.4.155
    # Redis服务器端口
    port: 6379
    # Redis服务器连接密码(如果有密码保护)
    password: 123456
    # Redis数据库编号,默认为0
    database: 0
    # 连接超时时间(毫秒)
    timeout: 15000
    lettuce:
      pool:
        # 最小空闲连接数
        min-idle: 0
        # 最大空闲连接数
        max-idle: 8
        # 最大活动连接数(连接池最大连接数)
        max-active: 8
        # 获取连接的最大等待时间(毫秒),-1表示无限等待
        max-wait: -1
      # 关闭连接池时最大等待时间(毫秒)
      shutdown-timeout: 100ms

配置项描述
spring.redis.hostRedis服务器的主机地址。
spring.redis.portRedis服务器的端口号。
spring.redis.passwordRedis服务器的密码(如果有密码的话)。
spring.redis.databaseRedis数据库的编号。默认情况下,Redis有16个数据库(从0到15),你可以选择使用哪一个。
spring.redis.timeout连接到Redis服务器的超时时间,单位为毫秒。
spring.redis.lettuce.pool.min-idle连接池中保持的最小空闲连接数。连接池会保持这些连接,以便可以更快速地获取到Redis连接。
spring.redis.lettuce.pool.max-idle连接池中保持的最大空闲连接数。当空闲连接数达到这个值时,多余的连接将被释放。
spring.redis.lettuce.pool.max-active连接池中允许的最大连接数。当连接数达到这个值时,新的连接请求将被阻塞,直到有连接被释放。
spring.redis.lettuce.pool.max-wait获取连接的最大等待时间,单位为毫秒。当连接池已经分配了所有连接,且当前连接数已经达到max-active时,新的连接请求将会等待,直到超过这个等待时间。如果设置为-1表示无限等待。
spring.redis.lettuce.pool.shutdown-timeout连接池关闭的超时时间,单位为毫秒。当应用程序关闭时,连接池会等待这段时间,以便让正在使用的连接完成操作。超过这个时间后,连接将被强制关闭。

3. 接口测试

@Api(tags = "redis操作接口")
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @GetMapping("keys")
    public ApiResult<Object> getKeys(@RequestParam(defaultValue = "*") String key) {
        return new ApiResult<>(this.stringRedisTemplate.keys(key));

    }

    @GetMapping("deleteKey")
    public ApiResult<Object> delete(String key) {
        this.stringRedisTemplate.delete(key);
        return new ApiResult<>();

    }

    @PostMapping("setOrIncrement")
    public ApiResult<Object> setString(String key, String value) {

        if (StringUtils.isEmpty(value)) {
            this.stringRedisTemplate.boundValueOps(key).increment();
        } else {
            this.stringRedisTemplate.boundValueOps(key).set(value);
        }
        String result = this.stringRedisTemplate.boundValueOps(key).get();
        return new ApiResult<>(result);

    }
}

三 进阶–redis指定配置启动[docker]

1.使用配置文件启动

上述的快速启动方式只适合开发阶段, 这种模式采用配置文件都是默认, 正式环境我们需要指定自己的配置文件及挂载数据目录.

1.1 创建redis工作目录

mkdir -p  /usr/local/docker/redis/data

1.2 创建redis.conf配置文件

vi /usr/local/docker/redis/redis.conf

#改成0.0.0.0,使redis可以外部访问
bind 0.0.0.0 
port 6380
#用守护线程的方式启动
daemonize no 
#给redis设置密码
requirepass 123456
#redis持久化默认是no 
appendonly yes

1.3 docker启动

注意:为了区分上面的简单启动, 配置文件方式docker启动,修改了默认端口 6379->6380 容器别名redis_01->redis_02

docker run \
-d \
-p 6380:6380 \
--name redis_02 \
-v /usr/local/docker/redis/redis.conf:/etc/redis/redis.conf \
-v /usr/local/docker/redis/data:/data \
redis:latest \
redis-server /etc/redis/redis.conf --appendonly yes 
  • -d redis 表示后台启动redis
  • -p 6380:6380 端口映射:前表示主机部分,:后表示容器部分。
  • –name redis_02 指定该容器名称,查看和进行操作都比较方便。
  • -v 挂载目录,规则与端口映射相同。
  • redis-server /etc/redis/redis.conf 以配置文件启动redis,加载容器内的conf文件,最终找到的是挂载的目录/usr/local/docker/redis.conf
  • appendonly yes 开启redis 持久化[AOF]

2.使用docker-compose快速搭建

上面的配置使用最简单的docke命令配置redis, 但是步骤太繁琐了, 接下来我们使用docker-compose一键部署redis

Docker Compose 是 Docker 官方提供的一个工具,用于定义和运行多容器的 Docker 应用。通过 Docker Compose,你可以使用一个 YAML 文件来配置应用程序的服务、网络和卷等方面的参数。通过运行一个简单的命令,你可以启动整个应用程序,包括其中的多个容器

2.1 创建一键启动脚本

完整复制下面代码,将创建一个docker-compose安装redis的shell脚本. 执行后面启停命令. 可以在任意docker环境快速启动redis环境服务搭建

cd ~
cat > redis_docker.sh <<EOF
#创建redis compose目录
mkdir -p /root/test/docker-compose-redis
cd /root/test/docker-compose-redis

#编写redis docker compose
cat > docker-compose.yaml << !EOF
version: '3'
services:
  redis:
    #image: redis:latest
    image: redis:6.2.7
    container_name: redis_simple
    restart: always
    ports:
      - 6379:6379
    volumes:
      - ./redis/redis.conf:/usr/local/etc/redis/redis.conf
      - ./redis/data:/data
    command:
      /bin/bash -c "redis-server /usr/local/etc/redis/redis.conf"
!EOF

#创建启动配置文件及数据目录data
mkdir -p redis/data
cat > ./redis/redis.conf << !EOF
#改成0.0.0.0,使redis可以外部访问
bind 0.0.0.0 
port 6379
#用守护线程的方式启动
daemonize no 
#给redis设置密码
requirepass 123456
#redis持久化默认是no 
appendonly yes
!EOF

EOF
chmod +x redis_docker.sh
./redis_docker.sh

2.1 docker-compose一键启停

# 启动redis
docker-compose -f /root/test/docker-compose-redis/docker-compose.yaml up -d
# 关闭redis
docker-compose -f /root/test/docker-compose-redis/docker-compose.yaml down

四 进阶–starter-data-redis自动装配原理

为什么我们直接引入redis的starter,配置属性后就可以直接使用redisTemplate呢, spring-boot-autoconfigure包下默认包含RedisAutoConfiguration, 引入依赖会触发自动装配的条件.如下图
@see org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration (spring-boot-autoconfigure:2.1.18.RELEASE)
在这里插入图片描述

五 进阶–自定义RedisTemplate

autoconfigure 提供RedisAutoConfiguration,创建的RedisTemplate和StringRedisTemplate默认value值分别使用
JDK和String的序列化方式.JDK序列化方式,当保存对象通过redis-cli 无法直观查看对象数据,因此自定义bean=“redisTemplate” 改用json序列化(注意beanName名字保持一致),这样就替代了自动装配生效的默认template
在这里插入图片描述

package com.demo.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;

/**
 *  Spring Redis 配置
 */
@Configuration
public class RedisConfig {
	
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        // Value(String)和HashValue(hash) key序列化指定String方式,默认为JDK序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // Value(String)和HashValue(hash) value序列化指定json方式,默认为JDK序列化
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

效果:
在这里插入图片描述

六 进阶–使用redis缓存

SpringBoot_redis使用实战(二)_缓存

七 进阶–api操作不同数据结构

TODO 演示redisTemplate

八 进阶–集成redission使用分布式锁

TODO


参考文档

  1. Redis详解(十二)------ 缓存穿透、缓存击穿、缓存雪崩
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Over 35 recipes to help you build, test, and run Spring applications using Spring Boot About This Book Learn to create different types of Spring Boot applications, configure behavior, and add custom components Become more efficient in testing, deploying, and monitoring Spring Boot based applications This is a practical guide that will help Spring developers to develop and deploy applications using Spring Boot Who This Book Is For If you are a Spring Developer who has good knowledge level and understanding of Spring Boot and application development and now want to learn efficient Spring Boot development techniques in order to make the existing development process more efficient, then this book is for you. What You Will Learn Create Spring Boot applications from scratch Configure and tune web applications and containers Create custom Spring Boot auto-configurations and starters Use Spring Boot Test framework with JUnit, Cucumber, and Spock Configure and tune web applications and containers Deploy Spring Boot as self-starting executables and Docker containers Monitor data using DropWizard, Graphite, and Dashing In Detail Spring Boot is Spring's convention-over-configuration solution. This feature makes it easy to create Spring applications and services with absolute minimum fuss. Spring Boot has the great ability to be customized and enhanced, and is specifically designed to simplify development of a new Spring application. This book will provide many detailed insights about the inner workings of Spring Boot, as well as tips and recipes to integrate the third-party frameworks and components needed to build complex enterprise-scale applications. The book starts with an overview of the important and useful Spring Boot starters that are included in the framework, and teaches you to create and add custom Servlet Filters, Interceptors, Converters, Formatters, and PropertyEditors to a Spring Boot web application. Next it will cover configuring custom routing rules and patterns, adding additional static asset paths, and adding and modifying servlet container connectors and other properties such as enabling SSL. Moving on, the book will teach you how to create custom Spring Boot Starters, and explore different techniques to test Spring Boot applications. Next, the book will show you examples of configuring your build to produce Docker images and self-executing binary files for Linux/OSX environments. Finally, the book will teach you how to create custom health indicators, and access monitoring data via HTTP and JMX. Style and approach This book is a cohesive collection of recipes that provide developers with a set of connected guidelines on how to build, configure, and customize their application, starting from the design and development stages, all the way through testing, deployment, and production monitoring. Table of Contents Chapter 1. Getting Started with Spring Boot Chapter 2. Configuring Web Applications Chapter 3. Web Framework Behavior Tuning Chapter 4. Writing Custom Spring Boot Starters Chapter 5. Application Testing Chapter 6. Application Packaging and Deployment Chapter 7. Health Monitoring and Data Visualization

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值