Spring Boot中使用Redis數據庫
Spring Boot中除了對常用的關系型數據庫提供了優秀的自動化支持之外,對于很多NoSQL數據庫一樣提供了自動化配置的支持,包括:Redis, MongoDB, Elasticsearch, Solr和Cassandra。
使用Redis
Redis是一個開源的使用ANSI C語言編寫、支持網絡、可基于內存亦可持久化的日志型、Key-Value數據庫。
引入依賴
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> 的實現。
除了String類型,實戰中我們還經常會在Redis中存儲對象,這時候我們就會想是否可以使用類似 RedisTemplate<String, User> 來初始化并進行操作。但是Spring Boot并支持直接使用,需要我們自己實現 RedisSerializer<T> 接口來對傳入對象進行序列化和反序列化,下面我們通過一個實例來完成對象的讀寫操作。
- 創建要存儲的對象:User
public class User implements Serializable {
private static final long serialVersionUID = -1L;
private String username;
private Integer age;
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
// 省略getter和setter
}
- 實現對象的序列化接口
public class RedisObjectSerializer implements RedisSerializer<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();
static final byte[] EMPTY_ARRAY = new byte[0];
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Cannot deserialize", ex);
}
}
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}
private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}
- 配置針對User的RedisTemplate實例
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, User> template = new RedisTemplate<String, User>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}
- 完成了配置工作后,編寫測試用例實驗效果
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
@Autowired
private RedisTemplate<String, User> redisTemplate;
@Test
public void test() throws Exception {
// 保存對象
User user = new User("超人", 20);
redisTemplate.opsForValue().set(user.getUsername(), user);
user = new User("蝙蝠俠", 30);
redisTemplate.opsForValue().set(user.getUsername(), user);
user = new User("蜘蛛俠", 40);
redisTemplate.opsForValue().set(user.getUsername(), user);
Assert.assertEquals(20, redisTemplate.opsForValue().get("超人").getAge().longValue());
Assert.assertEquals(30, redisTemplate.opsForValue().get("蝙蝠俠").getAge().longValue());
Assert.assertEquals(40, redisTemplate.opsForValue().get("蜘蛛俠").getAge().longValue());
}
}
當然spring-data-redis中提供的數據操作遠不止這些,本文僅作為在Spring Boot中使用redis時的配置參考,更多對于redis的操作使用,請參考 Spring-data-redis Reference 。
來自: http://blog.didispace.com/springbootredis/