spring boot 简单整合 Redis

复制代码
1.添加依赖

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>


2.配置

spring.redis.host=42.192.50.187
spring.redis.port=6379
spring.redis.password=redis@123
spring.redis.database=0
spring.redis.timeout=10000ms
# 连接池 - 最大连接数,默认:8
spring.redis.lettuce.pool.max-active=8
# 连接池 - 最大连接阻塞等待时间,默认:-1
spring.redis.lettuce.pool.max-wait=10000ms
# 连接池 - 最大、最小空闲连接数,最大默认:8,最小默认:0
spring.redis.lettuce.pool.max-idle=200
spring.redis.lettuce.pool.min-idle=5




3.配置类

/**
 * 配置 RedisTemplate 序列化
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // String 类型 - 序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        // hash 类型 - 序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        // 注入连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        return redisTemplate;
    }

}

4.使用

# 注入依赖;
    @Autowired
    private RedisTemplate redisTemplate;

存储数据:redisTemplate.opsForValue().set("user:" + ticket, user);
相关推荐
新程快咖员11 分钟前
【编程分享】如何去覆盖lombok中使用@Builder注解生成的Builder类的ToString()方法?
后端
程序员小假12 分钟前
十个JVM核心知识点【全文万字保姆级详细讲解】
java·后端
盖世英雄酱5813617 分钟前
小小的改动,竟然效率提高了1000倍
数据库·后端
韩zj17 分钟前
springboot调用python文件,python文件使用其他dat文件,适配windows和linux,以及docker环境的方案
windows·spring boot·python
泉城老铁17 分钟前
springboot对接钉钉,发送钉钉消息
java·前端·后端
whoarethenext18 分钟前
基于libevent写一个服务器(附带源码)
linux·运维·服务器·c++·后端
八股文领域大手子23 分钟前
从接口400ms到20ms,记录一次JVM、MySQL、Redis的混合双打
jvm·数据库·redis·mysql·jar
阿里云华为云天翼云腾讯云代理商_小李29 分钟前
‌腾讯云国际站代理商:如何搭建邮件服务器?
后端
洛卡卡了33 分钟前
Go + Gin 实现动态定时任务系统:从静态注册到动态调度与日志记录
后端·go
AronTing36 分钟前
13-Java并发编程性能优化终极指南:从原理到企业级实战
java·后端·面试