在Spring中调用Redis数据库

一、添加依赖
在Pom文件中添加如下内容

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

二、修改application.properties文件
在application.properties文件中添加如下内容

################################# Redis相关配置 #################################
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.database=0
spring.redis.timeout=10000
#Redis过期时间
spring.redis.expire=60000

三、编写Redis配置类

package com.example.redis_demo;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * redis配置类
 */
@Configuration
public class RedisConfig {
    //缓存过期时间
    @Value("${spring.redis.expire}")
    private Long expire;

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        //设置在生成 json 串时,对象中的成员的可见性
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //存储到redis的json将是有类型的数据
        //指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    //@Cacheable注解字符集编码配置
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config.entryTtl(Duration.ofMinutes(expire))//缓存过期时间
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));

        return RedisCacheManager
                .builder(factory)
                .cacheDefaults(config)
                .build();
    }
}

四、编写Redis服务类

package com.example.redis_demo;

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

import java.util.concurrent.TimeUnit;

@Component
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 存缓存
     * @param key
     * @param value
     * @param timeOut//秒
     */
    public void set(String key ,String value,Long timeOut){
        redisTemplate.opsForValue().set(key,value,timeOut, TimeUnit.SECONDS);
    }

    /**
     * 取缓存
     * @param key
     * @return
     */
    public String get(String key){
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 清除缓存
     * @param key
     */
    public void del(String key){
        redisTemplate.delete(key);
    }
}

五、测试

package com.example.redis_demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RedisDemoApplicationTests {
    @Autowired
    RedisService redisService;
    @Test
    void setKey() {
        String key="名字";
        String value="蔡胶芬01";
        long timeout=30;//秒
        redisService.set(key,value,timeout);
    }
    @Test
    void redKey() {
        String key="名字";
        System.out.println(redisService.get(key));
    }
    @Test
    void delKey() {
        String key="名字";
        redisService.del(key);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot集成Redis可以通过以下步骤实现: 1. 添加Redis依赖:在Spring Boot项目的pom.xml文件添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息:在application.properties文件添加以下配置信息: ``` spring.redis.host=redis服务器IP spring.redis.port=redis服务器端口号 spring.redis.password=redis密码 ``` 3. 创建RedisTemplate:在Java代码创建RedisTemplate对象,并注入到需要使用Redis的类。 ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); redisTemplate.afterPropertiesSet(); return redisTemplate; } } ``` 4. 使用RedisTemplate操作Redis:通过RedisTemplate对象的方法,可以进行各种Redis操作,如set、get、delete等。 以上是Spring Boot集成Redis的基本步骤,具体实现还需根据具体需求进行配置和调整。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发框架,它提供了简化的配置和开箱即用的功能,使得我们可以快速构建和部署应用程序。而Redis是一个高性能的键值对存储数据库,它常被用于缓存和数据存储。 在Spring Boot集成Redis,首先需要引入相关的依赖。可以通过Maven或Gradle来引入spring-boot-starter-data-redis依赖,该依赖会自动引入Redis相关的配置和依赖库。 然后,在配置文件添加Redis的连接信息。在application.properties或application.yml,可以配置Redis的主机地址、端口号、密码等信息。 接下来,在需要使用Redis的地方,可以使用@Autowired注解来注入RedisTemplate对象。RedisTemplate是Spring提供的操作Redis的模板类,它封装了常用的操作方法。 使用RedisTemplate,可以通过调用其对应的方法来操作Redis数据库,比如设置键值对、获取键值对、设置过期时间等。 除了RedisTemplate,Spring Boot还提供了RedisCacheManager类用于缓存管理,它可以通过注解@Configuration和@EnableCaching来启用缓存功能。在需要缓存的方法上使用@Cacheable注解,就可以将方法的返回值缓存到Redis,下次调用时可以直接从缓存获取,提高了性能。 总的来说,集成RedisSpring Boot,只需要引入依赖、配置连接信息,然后通过RedisTemplate操作Redis数据库,或使用RedisCacheManager进行数据缓存管理就可以了。这样可以简化我们与Redis的交互,提高开发效率和应用性能。 ### 回答3: 在Spring Boot,集成Redis可以通过以下步骤实现: 1. 在pom.xml文件添加Redis的依赖库: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties或application.yaml文件配置Redis连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建一个Redis配置类,用于配置Redis连接工厂: ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean @Override public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { // 生成缓存的key,可以根据实际需求定制 return ""; } }; } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); // 设置value的序列化方式 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // 设置key的序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } } ``` 4. 在需要使用Redis的类,通过注入RedisTemplate来操作Redis: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void cacheData(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getData(String key) { return redisTemplate.opsForValue().get(key); } ``` 通过以上步骤,我们就成功在Spring Boot集成了Redis,可以方便地使用Redis进行缓存、存储和读取数据。在配置Redis时,我们需要根据实际情况修改host、port和password等配置项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值