首先在pom.xml中引入所需的依赖:java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
而后在applications.properties中添加相关配置:redis
### 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
文件:spring
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方法来操做简单属性数据外,还提供如下数据访问方法:缓存
来操做复杂类型的数据。服务器