Spring Boot 整合之Redis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40369944/article/details/83901862

在添加 redis 依赖包启动项目后,Spring Boot 会自动配置 RedisCacheManger 和 RedisTemplate 的 Bean。如果开发者不想使用 Spring Boot 写好的 Redis 缓存,而是想使用其 API 自己实现缓存功能、消息队列或分布式锁之类的需求时,可以继续往下浏览。

Spring Data Redis 为我们提供 RedisTemplate 和 StringRedisTemplate 两个模板进行数据操作,它们主要 的访问方法如下:

方法 说明
opsForValue() 操作简单属性的数据
opsForList() 操作含有 list 的数据
opsForSet() 操作含有 set 的数据
opsForZSet() 操作含有 zset 的数据
opsForHash() 操作含有 hash 的数据

1.导入依赖

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

2.配置连接属性

# redis 配置
spring.redis.host=47.106.8.233
spring.redis.port=6379
spring.redis.password=redis123
# 缓存过期时间,单位毫秒
spring.cache.redis.time-to-live=60000s

3.创建RedisDao

@Component
public class RedisDao {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, String value) {
        this.stringRedisTemplate.opsForValue().set(key, value);
    }

    public String get(String key) {
        return this.stringRedisTemplate.opsForValue().get(key);
    }

    public void delete(String key) {
        this.stringRedisTemplate.delete(key);
    }
}

4.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDaoTest {

  @Autowired
  private RedisDao redisDao;

  @Test
  public void testSet() {
    String key = "name";
    String value = "zhangsan";

    this.redisDao.set(key, value);
  }

  @Test
  public void testGet() {
    String key = "name";
    String value = this.redisDao.get(key);
    System.out.println(value);
  }

  @Test
  public void testDelete() {
    String key = "name";
    this.redisDao.delete(key);
  }
}

猜你喜欢

转载自blog.csdn.net/qq_40369944/article/details/83901862