javascript
Spring Boot中使用Redis数据库
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> |
注意不同版本的spring boot下,redis的starter依賴名略有不同,如果上面的不行,可以嘗試spring-boot-starter-data-redis
參數配置
按照慣例在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。
| (SpringJUnit4ClassRunner.class) (Application.class) public class ApplicationTests { private StringRedisTemplate stringRedisTemplate; 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實例
public class RedisConfig { JedisConnectionFactory jedisConnectionFactory() { return new JedisConnectionFactory(); } 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; } } |
- 完成了配置工作后,編寫測試用例實驗效果
(SpringJUnit4ClassRunner.class) (Application.class) public class ApplicationTests { private RedisTemplate<String, User> redisTemplate; 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。
代碼示例
本文的相關例子可以查看下面倉庫中的chapter3-2-5目錄:
- Github:https://github.com/dyc87112/SpringBoot-Learning
- Gitee:https://gitee.com/didispace/SpringBoot-Learning
如果您覺得本文不錯,歡迎Star支持,您的關注是我堅持的動力!
總結
以上是生活随笔為你收集整理的Spring Boot中使用Redis数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker系列之二:基于容器的自动构建
- 下一篇: 深入浅出不可思议的中文分词技术