springboot 与 Redis整合

SpringBoot 操作数据:Spring-data jpa jdbc mongodb redis!
SpringData 也是和SpringBoot 齐名的项目!
说明:在SpringBoot2.X 之后,原来使用的jedis被替换成了lettuce
jedis: 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用jedis pool 连接池,更新BIO模式
lettuce: 采用netty ,实例可以在多个线程中进行共享,不存在线程不安全的情况,可以减少线程数据,更想NIO模式

整合步骤

引入依赖

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

在这里插入图片描述

 @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )  
    我们可以自定义RedisTemplate
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    // 使用默认的RedisTemplate 没有过多的设置,但是我们实际当中一般都需要进行序列化
    //<Object, Object> 需要强转 <String, Object>
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    // 由于String类型是Redis经常使用的类型所以这个地方单独写了一个StringRedisTemplate 
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

配置相关信息

在这里插入图片描述
根据实际中进行配置既可

测试

 */
@RestController
public class HelloController {

    @Resource
    private RedisTemplate redisTemplate;
    @RequestMapping("hello")
    public String hell(){
        redisTemplate.opsForValue().set("javakey","ddd");
        Object javakey = redisTemplate.opsForValue().get("javakey");
        System.out.printf(javakey.toString());
        redisTemplate.opsForValue().set("中文","我也是中文");
        System.out.println(redisTemplate.opsForValue().get("中文").toString());
        return "hello";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值