Spring Boot中除了对经常使用的关系型数据库提供了优秀的自动化支持以外,对于不少NoSQL数据库同样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch, Solr和Cassandra。java
任选其一git
CentOs7.3 搭建 Redis-4.0.1 单机服务github
CentOs7.3 搭建 Redis-4.0.1 Cluster 集群服务redis
代码我已放到 Github ,导入 spring-boot-examples 项目spring
github github.com/souyunku/sp…数据库
在项目中添加 spring-boot-starter-data-redis
依赖segmentfault
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
复制代码
@Configuration
public class RedisConfig {
private Logger LOG = LoggerFactory.getLogger(RedisConfig.class);
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> template = new RedisTemplate<String, String>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
LOG.info("create RedisTemplate success");
return template;
}
}
复制代码
application.properties
bash
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# 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
复制代码
public class CacheUtils {
@Resource
private RedisTemplate<String, String> redisTemplate;
private static CacheUtils cacheUtils;
@PostConstruct
public void init() {
cacheUtils = this;
cacheUtils.redisTemplate = this.redisTemplate;
}
/** * 保存到hash集合中 * * @param hName 集合名 * @param key * @param value */
public static void hashSet(String hName, String key, String value) {
cacheUtils.redisTemplate.opsForHash().put(hName, key, value);
}
/** * 从hash集合里取得 * * @param hName * @param key * @return */
public static Object hashGet(String hName, String key) {
return cacheUtils.redisTemplate.opsForHash().get(hName, key);
}
/** 省略 N 多方法 。。。。。。 */
}
复制代码
@Configuration
@Import({RedisConfig.class, CacheUtils.class})
public class RedisAutoConfiguration {
}
复制代码
import io.ymq.redis.utils.CacheUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import io.ymq.redis.run.Application;
import org.springframework.test.context.junit4.SpringRunner;
/** * 描述:测试类 * * @author yanpenglei * @create 2017-10-16 13:18 **/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class BaseTest {
@Test
public void test() throws Exception {
CacheUtils.hashSet("test", "ymq", "www.ymq.io");
System.out.println(CacheUtils.hashGet("test", "ymq"));
}
}
复制代码
代码我已放到 Github ,导入 spring-boot-examples 项目服务器
github github.com/souyunku/sp…app