SpringBoot整合Redis

安装Redis

下载链接https://github.com/MicrosoftArchive/redis/releases/tag/win-3.2.100

服务器启动

  1. cmd进入安装目录下
  2. 启动命令:redis-server.exe redis.windows.conf
  3. 输入命令后可能会报下面的错误,这是Redis的一个bug,解决方法。
    1. 另开一个cmd中输入:redis-cli.exe
    2. 输入:shutdown,再输入:exit,后回车,退出客户端。
  4. 重新输入命令:redis-server.exe redis.windows.conf
  5. 另开一个cmd中输入:redis-cli.exe

在SpringBoot项目中配置Redis

application.yml中

spring:
  redis:
    host: localhost  #默认就是localhost
    port: 6379       #默认就是6379

RedisTemplate

RedisTemplate以对象作为key和value,内部对数据进行序列化。

客户端默认是以字符串作为键值对进行存储和读取,这种方式不能读取在客户端存储的信息,客户端也不能读出程序所写入的信息。

@SpringBootTest()
class Xin1ApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;  //操作Redis的对象,默认以对象为key-value

    @Test
    void set(){
        //存储键值对
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set("age",33);

        //存储键对(键值对)
        HashOperations hash = redisTemplate.opsForHash();
        hash.put("info", "msg", "world");
        hash.put("info", "msg2", "world2");
    }

    @Test
    void contextLoads() {
        //读取键值对
        ValueOperations ops = redisTemplate.opsForValue();
        System.out.println(ops.get("age"));

        //读取键对(键值对)
        HashOperations hash = redisTemplate.opsForHash();
        System.out.println(hash.get("info", "msg"));
        System.out.println(hash.get("info", "msg2"));
    }
}

在客户端查看在程序中保存的key-value会发现写进去的值是序列化之后的。

 StringRedisTemplate

这种方式可以读取在客户端中存储的信息,也可以在客户端中读取程序所写的信息。

如果只使用字符类型的键值对,推荐使用!

@SpringBootTest()
class Xin1ApplicationTests {

    @Autowired
    private StringRedisTemplate redis;  //默认以字符串类型的键值对

    @Test
    void set(){
        //存储键值对
        ValueOperations<String, String> ops = redis.opsForValue();
        ops.set("age","33");

        //存储键对(键值对)
        HashOperations<String, Object, Object> hash = redis.opsForHash();
        hash.put("info", "msg", "world");
        hash.put("info", "msg2", "world2");
    }

    @Test
    void contextLoads() {
        //读取键值对
        ValueOperations<String, String> ops = redis.opsForValue();
        System.out.println(ops.get("age"));

        //读取键对(键值对)
        HashOperations<String, Object, Object> hash = redis.opsForHash();
        System.out.println(hash.get("info", "msg"));
        System.out.println(hash.get("info", "msg2"));
    }
}

Jedis和Lettuce

默认使用的Lettuce作为客户端。

Jedis是同步的,不支持异步,Jedis客户端实例不是线程安全的,需要每个线程一个Jedis实例,一般通过连接池来使用Jedis。

Lettuce是基于Netty框架的事件驱动的Redis客户端,其方法调用是异步的,Lettuce的API也是线程安全的,所以多个线程可以操作单个Lettuce连接来完成各种操作,同时Lettuce也支持连接池。

 

 

使用Jedis 

添加依赖

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

配置redis

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值