spring-boot集成redis

添加maven依赖

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

配置Redis连接信息

spring:
  redis:
    host: localhost
    port: 6379
    password:

使用Redis

redis起步依赖自动注入了2个操作redis的Bean

  • RedisTemplate<K, V> - 用于操作Redis
  • StringRedisTemplate - 是RedisTemplate的子类,用于操作String类型的键值对
@RestController
public class MyController
{
    private final RedisTemplate<String,String> redisTemplate;
    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public MyController(RedisTemplate<String,String> redisTemplate,StringRedisTemplate stringRedisTemplate)
    {
        this.redisTemplate = redisTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @GetMapping("/hello")
    public Object hello()
    {
        // 获取一个操作值类型的Operations
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        // 保存
        valueOperations.set("hello","world");
        // 获取
        String hello = valueOperations.get("hello");
        return hello;
    }
}

更换Jedis

RedisTemplate默认使用Lettuce作为Redis客户端,这是一个使用Netty实现高并发安全库。

Jedis是直连Redis Server的,没有保证线程安全。

要想使用Jedis,只需要2步

引入依赖

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

配置redis

spring:
  redis:
    client-type: jedis
posted @ 2021-07-06 13:58  lypzzzz  阅读(54)  评论(0)    收藏  举报