码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot集成Redis缓存

时间:2018-11-08 23:20:28      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:复杂   imp   package   tab   not   hash   name   pom.xml   .data   

首先在pom.xml中引入所需的依赖:

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

然后在applications.properties中添加相关配置:

### Redis缓存配置
### 默认redis数据库为db0
spring.redis.database=0
### 服务器地址,默认为localhost
spring.redis.host=localhost
### 链接端口,默认为6379
spring.redis.port=6379
### redis密码默认为空
spring.redis.password=

然后编辑src/test/java下的TestApplicationTests.java文件:

package com.zifeiy.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
    
    @Resource
    private RedisTemplate redisTemplate;
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Test
    public void testRedis() {
        redisTemplate.opsForValue().set("name", "zifeiy");
        String name = (String) redisTemplate.opsForValue().get("name");
        System.out.println("1: " + name);
        redisTemplate.delete("name");
        redisTemplate.opsForValue().set("name", "zifeiy");
        name = stringRedisTemplate.opsForValue().get("name");
        System.out.println("2: name");
    }
}

输出结果如下:

1: zifeiy
2: name

这里的RedisTemplate和StringRedisTemplate都是Redis Data Redis为我们提供的模板类,用来对Redis数据库进行操作。他们除了提供opsForValue方法来操作简单属性数据外,还提供以下数据访问方法:

  • opsForList
  • opsForSet
  • opsForZSet
  • opsForHash

来操作复杂类型的数据。

Spring Boot集成Redis缓存

标签:复杂   imp   package   tab   not   hash   name   pom.xml   .data   

原文地址:https://www.cnblogs.com/zifeiy/p/9932449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!