本文講解Spring Boot基礎下,如何整合Redis,編寫數據訪問。
原文地址:Spring Boot 揭祕與實戰(二) 數據存儲篇 - Redis
博客地址:blog.720ui.com/javascript
修改 POM 文件,添加 spring-boot-starter-redis 依賴。java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>複製代碼
在 src/main/resources/application.properties 中配置數據源信息。git
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0複製代碼
在 src/main/resources/config/redis.properties 中配置數據源信息。github
# redis
redis.host=localhost
redis.port=6379
redis.password=
redis.database=1複製代碼
經過 Java Config 建立redisTemplate。redis
@Configuration
@PropertySource("classpath:config/redis.properties")
public class RedisConfig {
@Autowired
private Environment env;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName(env.getProperty("redis.host").trim());
jedisConnectionFactory.setPort(Integer.parseInt(env.getProperty("redis.port").trim()));
jedisConnectionFactory.setPassword(env.getProperty("redis.password").trim());
jedisConnectionFactory.setDatabase(Integer.parseInt(env.getProperty("redis.database").trim()));
jedisConnectionFactory.setUsePool(true);
jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}複製代碼
@Repository
public class RedisBaseDao {
@Resource(name="redisTemplate")
protected ValueOperations<String, String> valueOperations;
public void addValue(String key, String value){
valueOperations.set(key, value);
}
public String getValue(String key){
return valueOperations.get(key);
}
}複製代碼
@Repository
public class ValueRedisDao {
@Autowired
public RedisBaseDao redisBaseDao;
private String getKey(){
return "param";
}
public void save(String param){
this.redisBaseDao.addValue(this.getKey(), param);
}
public String getParam(){
return this.redisBaseDao.getValue(this.getKey());
}
}複製代碼
編寫單元測試用例,測試Redis是否正常工做。spring
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(WebMain.class)
public class RedisTest {
@Autowired
private ValueRedisDao valueRedisDao;
@Test
public void test() throws Exception {
this.valueRedisDao.save("LiangGzone");
System.out.println(this.valueRedisDao.getParam());
}
}複製代碼
上面這個簡單的案例,讓咱們看到了 Spring Boot 整合 Redis 的整個流程。實際上,與 Spring 4 中 經過 Spring Data Redis 整合 Redis 並沒有二意, Spring Boot 默認集成了一些配置信息,可是我的更加偏向於方案二的手動建立方式,爲何呢,由於更方便擴展。springboot
相關示例完整代碼: springboot-action微信
(完)app
更多精彩文章,盡在「服務端思惟」微信公衆號!
spring-boot