In addition to providing excellent automation support for commonly used relational databases, Spring boot provides automated configuration support for many NoSQL databases, including: Redis, MongoDB, Elasticsearch, SOLR, and Cassandra.
Using Redis
Redis is an open source, Key-value database that is written in ANSI C language, supports the network, and can be persisted based on memory.
- Redis official website
- Redis Chinese Community
Introducing Dependencies
Spring boot provides a data access framework spring data Redis based on Jedis. You can spring-boot-starter-redis
configure dependencies by introducing them.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-redis</artifactid></dependency>
Parameter configuration
Follow the convention to application.properties
join the Redis server-side configuration, as described below:
# Redis (redisproperties) # Redis Database index (default = 0) spring.redis.database=0# Redis server address spring.redis.host=localhost# Redis Server connection Port spring.redis.port=6379# Redis Server connection password (default is empty) spring.redis.password=# Connection pool Maximum number of connections (using negative values for No limit) spring.redis.pool.max-active=8# connection pool maximum blocking wait time (using negative values means there is no limit) spring.redis.pool.max-wait=-1# The maximum idle connection in the connection pool spring.redis.pool.max-idle=8# the minimum idle connection in the connection pool spring.redis.pool.min-idle=0# connection time-out (in milliseconds) spring.redis.timeout =0
Where the configuration of spring.redis.database usually uses 0, Redis can set the number of databases when configured, the default is 16, can be understood as the database schema
Test access
Write test cases to illustrate how to access Redis.
@RunWith (Springjunit4classrunner.class) @SpringApplicationConfiguration (application.class) public class applicationtests {@Autowiredprivate stringredistemplate stringredistemplate; @Testpublic void Test () throws Exception { Save String Stringredistemplate.opsforvalue (). Set ("AAA", "111"); Assert.assertequals ("111", Stringredistemplate.opsforvalue (). Get ("AAA"));} }
This very simple test case demonstrates how to StringRedisTemplate
perform a redis read and write operation with an automatically configured object, which can be noted from the naming of the supported string types. If you have used Spring-data-redis developers must be familiar with the RedisTemplate<K, V>
interface, StringRedisTemplate
RedisTemplate<String, String>
the equivalent of the implementation.
Source Source
Spring Boot Tutorial (33) using the Redis database (1)