springboot中redis的簡單操作

Mars-xq發表於2018-12-19

簡單示例:

application.properties:

## Redis資料庫索引(使用的資料庫(0-15),預設為0)
spring.redis.database=0

## 連線URL,將覆蓋主機,埠和密碼(使用者將被忽略),
## 例如:redis://user:password@example.com:6379
spring.redis.url=
## Redis伺服器主機: 127.0.0.1
spring.redis.host=localhost
## Redis伺服器連線密碼(預設為空)
spring.redis.password=
## Redis伺服器連線埠
spring.redis.port=6379

## 啟用SSL支援
spring.redis.ssl=false

## 連線超時時間(毫秒)
spring.redis.timeout=0
## 連線池最大連線數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=8
## 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1
## 連線池中的最大空閒連線
spring.redis.jedis.pool.max-idle=8
## 連線池中的最小空閒連線
spring.redis.jedis.pool.min-idle=0

## cluster	[ˈklʌstə(r)] 叢集
spring.redis.cluster.nodes=
spring.redis.cluster.max-redirects=

## sentinel	[ˈsentɪnl] 哨兵
spring.redis.sentinel.master=
spring.redis.sentinel.nodes=

## lettuce	[ˈletɪs]   萵苣、生菜
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100

pom.xml:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

定義redis的操作類

@Repository
public class RedisDao {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setKey(String key, String value) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set(key, value, 1, TimeUnit.MINUTES);//1分鐘過期
    }

    public String getValue(String key) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        return valueOperations.get(key);
    }
}

測試:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Test
    public void contextLoads() {
    }

    public static Logger logger = LoggerFactory.getLogger(DemoApplicationTests.class);

    @Autowired
    RedisDao redisDao;

    @Test
    public void testRedis() {
        redisDao.setKey("name", "xq");
        redisDao.setKey("age", "18");
        logger.info(redisDao.getValue("name"));
        logger.info(redisDao.getValue("age"));
    }

}

其他

StringRedisTemplate 與 RedisTemplate關係

public class StringRedisTemplate extends RedisTemplate<String, String> {

RedisAutoConfiguration

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

}

@ConditionalOnClass :
該註解的引數對應的類必須存在,否則不解析該註解修飾的配置類;

@ConditionalOnMissingBean :
該註解表示,如果存在它修飾的類的bean,則不需要再建立這個bean;
可以給該註解傳入引數例如@ConditionOnMissingBean(name = “example”),
這個表示如果name為“example”的bean存在,這該註解修飾的程式碼塊不執行。
判斷是否執行初始化程式碼,即如果使用者已經建立了bean,則相關的初始化程式碼不再執行。

相關文章