Spring Boot集成Redis緩存

首先在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方法來操做簡單屬性數據外,還提供如下數據訪問方法:緩存

  • opsForList
  • opsForSet
  • opsForZSet
  • opsForHash

來操做複雜類型的數據。服務器

相關文章
相關標籤/搜索