Spring Boot中使用NoSQL数据库非常方便,全程自动化的配置支持,从官网(1.5.2.RELEASE)上说明中可以看出,它支持的NoSql数据有:Redis 、MongoDB、 Neo4j 、Gemfire、 Solr、 Elasticsearch、 Cassandra、 Couchbase、 LDAP等。下文开始演示Redis的应用(坑已挖深,放心入坑)。
访问Redis
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
-
启动本地Redis Server
Paste_Image.png
PS: 因为只是编写入门使用,所以采用Spring Boot的默认Redis配置,下面会加入文件配置参数说明(You can inject an auto-configured RedisConnectionFactory, StringRedisTemplate or vanilla RedisTemplate instance as you would any other Spring Bean. By default the instance will attempt to connect to a Redis server using localhost:6379)
编写单元测试用例
import com.Application;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/**
* Description:
* author: 慢慢来了
* date: 2017/3/16 17:39
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisTest {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void setString(){
redisTemplate.opsForValue().set("hello" , "world! Redis");
String value = redisTemplate.opsForValue().get("hello");
Assert.assertEquals("world! Redis" , value);
}
@Test
public void setList(){
List<String> list = new ArrayList<>(5);
for(int i = 0 ; i < 5 ; i++) {
String val = "uid" + i;
list.add(val);
}
redisTemplate.opsForList().rightPushAll("list" , list);
//取第一个value
String listvalue = redisTemplate.opsForList().index("list" , 0);
Assert.assertEquals("uid0" , listvalue);
//取最后一个value
String lastValue = redisTemplate.opsForList().index("list" , 4);
Assert.assertEquals("uid4" , lastValue);
}
@Test
public void setSet(){
redisTemplate.opsForSet().add("setKey" , "aaa");
String setValue = redisTemplate.opsForSet().pop("setKey");
Assert.assertEquals("aaa" , setValue);
}
}
-
测试结果
- 登录redis-client

- Junit结果

加入参数配置
#数据库索引(默认为0)
spring.redis.database=0
# 服务器地址
spring.redis.host=localhost
# 服务器连接端口(默认6379)
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
参考资料:
http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/
网友评论