您的位置:首页 > 数据库 > Redis

Spring Cloud Spring Boot mybatis分布式微服务云架构(二十一)使用Redis数据库(1)

2018-03-05 10:18 1256 查看
Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch, Solr和Cassandra。

使用Redis

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库。

Redis官网

Redis中文社区

引入依赖

Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通过引入
spring-boot-starter-redis
来配置依赖关系。

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


参数配置

按照惯例在
application.properties
中加入Redis服务端的相关配置,具体说明如下:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

其中spring.redis.database的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16,可以理解为数据库的schema

测试访问

通过编写测试用例,举例说明如何访问Redis。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {

@Autowired
private StringRedisTemplate stringRedisTemplate;

@Test
public void test() throws Exception {

// 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));

}

}

通过上面这段极为简单的测试案例演示了如何通过自动配置的
StringRedisTemplate
对象进行Redis的读写操作,该对象从命名中就可注意到支持的是String类型。如果有使用过spring-data-redis的开发者一定熟悉
RedisTemplate<K, V>
接口,
StringRedisTemplate
就相当于
RedisTemplate<String, String>
的实现。


源码来源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐