广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot集成Redis流程详解
  • 547
分享到

SpringBoot集成Redis流程详解

SpringBoot集成RedisSpringBootRedis 2023-05-19 08:05:47 547人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录第一步,导入jar包第二步,编写配置类第三步,编写util类第四步,配置yml第一步,导入jar包 <!--Redis--> <depende

第一步,导入jar包

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

第二步,编写配置类

这是一个使用FastJSON序列化器,配置RedisTemplate的Spring Bean的Java类。该类使用了@Configuration注释来标识这是一个配置类,并使用@Bean注释来标识该方法是创建一个Bean的工厂方法。该方法名为redisTemplate,并使用了@ConditionalOnMissingBean注释,表示如果在上下文中没有StringRedisTemplate类型的Bean,则会自动创建一个该类型的Bean。该方法返回一个RedisTemplate类型的对象,该对象被配置为使用Fastjson序列化器,以便将对象序列化为JSON格式进行存储和检索。在方法内部,通过setConnectionFactory方法设置了RedisTemplate的连接工厂,并通过seTKEySerializer和setValueSerializer方法设置了键和值的序列化器。此外,该类还提供了一个名为stringRedisTemplate的方法,用于创建StringRedisTemplate类型的Bean。


import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    
    @Bean("getRedisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);


        
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    
    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}

第三步,编写util类

这段代码是一个基于Spring框架和Redis实现的工具类,封装了一些常见的操作方法。它依赖于另一个Redis配置类,通过@Autowired注解和@Qualifier注解来获取到RedisTemplate实例,从而进行操作。

具体的操作方法有:

  • set:设置键值对,将value存储到key中。
  • set:设置键值对并指定过期时间,将value存储到key中,并设置过期时间。
  • remove:删除一个或多个key对应的值。
  • exists:判断指定的key是否存在于缓存中。
  • get:获取指定key对应的值。

需要注意的是,get方法返回的是一个经过JSON序列化的字符串,而不是原始的对象。如果要使用对象,需要在调用get方法之后进行反序列化。

package com.wangfugui.apprentice.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtils {

    @Autowired
    @Qualifier("getRedisTemplate")
    private RedisTemplate redisTemplate;


    
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    
 
    public String get(String key) {
        return JSONObject.toJSONString(redisTemplate.opsForValue().get(key));
    }

}

第四步,配置yml

这是一个YAML格式的Spring Boot配置文件,配置了Redis数据库的连接信息,包括:

  • database: Redis数据库的编号,默认为0。
  • host: Redis服务器的IP地址。
  • port: Redis服务器的端口号。

这些配置信息会被Spring Boot自动加载并注入到对应的Bean中,可以在代码中使用这些Bean来连接和操作Redis数据库。

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379

好了,就是这么的简单,完整代码请移至SpringBoot+Redis查看

以上就是SpringBoot集成Redis流程详解的详细内容,更多关于SpringBoot集成Redis的资料请关注编程网其它相关文章!

--结束END--

本文标题: SpringBoot集成Redis流程详解

本文链接: https://www.lsjlt.com/news/212797.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作