Springboot连接Redis步骤

Redis的连接需要准备以下三步:

第一步 : 导入pom依赖或者看一下有没有下面的依赖 ,对于多个模块而言 ,只要有一个模块引入下面的依赖 ,所有模块会通用pom中的依赖

image-20230820114656201

第二步 : yml配置一下 ,localhost就是127.0.0.1

image-20230820120857283

第三步(选做,如果用的是StringRedisTemplate就不要写了,这个是给RedisTemplate服务的) : 编写配置类,注意@Configuration注解

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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(connectionFactory);
        // 创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 设置Key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        // 返回
        return template;
    }
}
  • RedisTemplate : 更多存的是对象

  • StringRedisTemplate : 泛型指定的是String。当存入对象时,会报错 :can not cast into String

第四步 : 测试

  • 注意测试类尽量使用绿色的test包,层级要和启动类保持一致

  • 注意导入以下包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

image-20230821112351103

  • 注意测试类上面要有@SpringBootTest注解 ,这个注解在pom中的依赖为import org.springframework.boot.test.context.SpringBootTest;image-20230820121615387

  • 注意@Test注解import org.junit.jupiter.api.Test;

image-20230820121732556

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值