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);
相关推荐
hai99long4 分钟前
DTP 模型:分布式事务处理的经典架构模型
后端
魔镜魔镜_谁是世界上最漂亮的小仙女4 分钟前
java-web开发
java·后端·架构
在肯德基吃麻辣烫18 分钟前
《Redis》缓存与分布式锁
redis·分布式·缓存
雷渊26 分钟前
微服务中为什么要设计不同的服务和不同的数据对象,体现了一个什么样的设计思想?
后端
无奈何杨1 小时前
CoolGuard风控中新增移动距离和移动速度指标
前端·后端
程序员爱钓鱼1 小时前
Go语言泛型-泛型约束与实践
前端·后端·go
寻月隐君1 小时前
保姆级教程:Zsh + Oh My Zsh 终极配置,让你的 Ubuntu 终端效率倍增
linux·后端·命令行
程序员爱钓鱼1 小时前
Go语言泛型-泛型对代码结构的优化
后端·google·go
这里有鱼汤1 小时前
“对象”?对象你个头!——Python世界观彻底崩塌的一天
后端·python
RainbowSea1 小时前
跨域问题(Allow CORS)解决(3 种方法)
java·spring boot·后端