Spring Boot集成Redis缓存

首先在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

来操作复杂类型的数据。

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