springboot整合redis

1.创建springboot项目 选择依赖

请添加图片描述

2.启动redis服务端 没有去官网下一个 ,傻瓜式安装(window版本)

请添加图片描述

3.在测试类中进行测试

package com.hdjy;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class NosqlRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    void set() {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("name","sun");
    }

    @Test
    void get() {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object name = valueOperations.get("name");
        System.out.println(name);
    }
}

执行结果
请添加图片描述

不过这种方法不能跟控制台的redis同步存取,因为控制台存入是字符串类型,RedisTemplate 是以对象的方式存入。如图
请添加图片描述

我们可以使用StringRedisTemplate解决

package com.hdjy;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class NosqlRedisApplicationTests2 {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Test
    void set() {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("name","sun");
    }

    @Test
    void get() {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object name = valueOperations.get("name");
        System.out.println(name);
    }
}

此时控制台也可以取到
在这里插入图片描述

请添加图片描述

如果想用jedis方式连接redis
1.引入依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

2.配置文件中配置信息

spring:
  redis:
    host: localhost
    port: 6379
    client-type: jedis

当不配置jedis时, client-type默认是lettuce

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值