<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>`
複製代碼
# REDIS (RedisProperties)
# Redis數據庫索引(默認爲0)
spring.redis.database=5
# 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
複製代碼
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate redisTemplate=new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
System.out.println("suscessful");
return redisTemplate;
}
}
複製代碼
@Autowired
private RedisTemplate redisTemplate;
@Resource(name="redisTemplate")
private HashOperations hashOperations;
@Resource(name="redisTemplate")
private ZSetOperations zSetOperations;
@Test
public void test1(){
redisTemplate.opsForValue().set("my","my");
Assert.assertEquals("my",redisTemplate.opsForValue().get("my"));
}
@Test
public void test2() {
Map<String, String> map = new HashMap<>();
map.put("age", "13");
map.put("name", "selrain");
hashOperations.putAll("test2", map);
Assert.assertEquals("13",hashOperations.get("test2","age"));
hashOperations.delete("test2","age","name");
}
@Test
public void test3(){
zSetOperations.add("selrain","selraion",1);
Assert.assertEquals("selraion",zSetOperations.range("selrain",0,1).iterator().next());
zSetOperations.remove("selrain","selraion");
}
@Test
public void test4(){
redisTemplate.execute((RedisConnection connection)->{
Jedis jedis=(Jedis)connection.getNativeConnection();
String s=jedis.set("test4","selrain","NX","EX",6000);
return s;
});
}
複製代碼
opsForValue、opsForHash、opsForZSet方法分別獲取對String、hash、Zset數據結構的操做實現,通常感受用這個就行了html
還能夠直接注入這些抽象,這樣就不用opsForHash,能夠直接用,爲何不一樣的類型能夠直接注入?看下這篇文章: www.cnblogs.com/chanedi/p/4…redis
execute方法給咱們暴露了RedisConnection,拿到連接後,咱們能夠轉換成Jedis的原始連接,從而可使用data redis不支持可是jedis支持的命令:好比測試代碼test4spring
想不想了解Redis的配置是如何初始化的?看這篇文章: my.oschina.net/u/3866531/b…數據庫
小尾巴走一波,歡迎關注個人公衆號,不按期分享編程、投資、生活方面的感悟:)編程