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);
相关推荐
丁总学Java7 分钟前
如何使用 maxwell 同步到 redis?
数据库·redis·缓存
蘑菇蘑菇不会开花~13 分钟前
分布式Redis(14)哈希槽
redis·分布式·哈希算法
爱吃南瓜的北瓜15 分钟前
Redis的Key的过期策略是怎样实现的?
数据库·redis·bootstrap
wn5311 小时前
【Go - 类型断言】
服务器·开发语言·后端·golang
bjzhang751 小时前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
flying jiang1 小时前
Spring Boot 入门面试五道题
spring boot
小菜yh1 小时前
关于Redis
java·数据库·spring boot·redis·spring·缓存
希冀1231 小时前
【操作系统】1.2操作系统的发展与分类
后端
GoppViper2 小时前
golang学习笔记29——golang 中如何将 GitHub 最新提交的版本设置为 v1.0.0
笔记·git·后端·学习·golang·github·源代码管理
爱上语文3 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring