springboot中redis使用list來快取資料
阿新 • • 發佈:2018-12-22
[@[email protected]]Let bygones be bygones*Love today!
一、應用背景
最近有個專案有這樣的背景:從mq訂閱了一批資料,收到資料後會將資料按照當前接收到的時間整點(分為單位,因為資料量比較大而且頻繁,且從快取拉取資料的時候也是每分鐘拉一次,批量讀取分析)快取到list,鍵以時間來標記,當然下面的程式碼並不是實現該背景功能。不多說,下面開始整個程式碼流程。
二、新增springboot專案redis依賴
<!--在pom.xml中spring-boot-starter-data-redis的依賴,Spring Boot2.x後底層不在是Jedis 如果做版本升級的朋友需要注意下--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
三、redis的簡單配置
# ============redis=========== # 在application.properties檔案中配置如下內容,由於Spring Boot2.x的改動, # 連線池相關配置需要通過spring.redis.lettuce.pool #或者spring.redis.jedis.pool進行配置了 spring.redis.host=localhost spring.redis.port=6379 # 一般來說是不用配置的,Spring Cache 會根據依賴的包自行裝配---》spring cache指定redis做快取 spring.cache.type=redis #spring.redis.password=root #根據需要 # 連線超時時間(毫秒) spring.redis.timeout=10000 # Redis預設情況下有16個分片,這裡配置具體使用的分片,預設是0 spring.redis.database=0 # 連線池最大連線數(使用負值表示沒有限制) 預設 8 spring.redis.lettuce.pool.max-active=8 # 連線池最大阻塞等待時間(使用負值表示沒有限制) 預設 -1 spring.redis.lettuce.pool.max-wait= # 連線池中的最大空閒連線 預設 8 spring.redis.lettuce.pool.max-idle=8 # 連線池中的最小空閒連線 預設 0 spring.redis.lettuce.pool.min-idle=0
四、在程式碼中增加一個redis的配置類
package com.zsh.config; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.io.Serializable; @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisCacheAutoConfiguration { @Bean public RedisTemplate<String,Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){ RedisTemplate<String, Serializable> template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } }
程式碼含義比較簡單,故不做過多說明。
五、示例測試程式碼
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisTemplate<String, Serializable> redisCacheTemplate;
@GetMapping("/list")
public List<String> getList(String param){
String key = "flow:list";//快取的key,
String[] params = param.split(",");
for(String s:params){
redisCacheTemplate.opsForList().rightPush(key,s);
}
List list = redisCacheTemplate.opsForList().range(key,0,-1);
return list;
}
}
END!
[@[email protected]]Let bygones be bygones*Love today!
Spend life with someone who makes you happy, not someone who you have to impress.