新聞中心
Spring WebFlux 是 Spring Framework 5.0中引入的新的響應(yīng)式web框架。與Spring MVC不同,它不需要Servlet API,是完全異步且非阻塞的,并且通過Reactor項(xiàng)目實(shí)現(xiàn)了Reactive Streams規(guī)范。

安裝簡易教程(適用 Mac/Linux)
下載并解壓
下載安裝包 redis-x.x.x.tar.gz
tar zxvf redis-2.8.17.tar.gz
編譯安裝
cd redis-x.x.x/
make
啟動(dòng) Redis
cd src
redis-server
如果需要運(yùn)行在守護(hù)進(jìn)程,設(shè)置 daemonize 從 no 修改成 yes,并指定運(yùn)行:redis-server redis.conf
結(jié)構(gòu)
類似上面講的工程搭建,新建一個(gè)工程編寫此案例。工程如圖:
目錄核心如下
pom.xml maven 配置
application.properties 配置文件
domain 實(shí)體類
controller 控制層,本文要點(diǎn)
新增 POM 依賴與配置
在 pom.xml 配置新的依賴:
org.springframework.boot
spring-boot-starter-data-redis-reactive
類似 MongoDB 配置,在 application.properties 配置連接 Redis :
## Redis 配置
## Redis服務(wù)器地址
spring.redis.host=127.0.0.1
## Redis服務(wù)器連接端口
spring.redis.port=6379
## Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
# 連接超時(shí)時(shí)間(毫秒)
spring.redis.timeout=5000
默認(rèn) 密碼為空,這里注意的是連接超時(shí)時(shí)間不能太少或者為 0 ,不然會(huì)引起異常 RedisCommandTimeoutException: Command timed out。
對(duì)象
修改 org.spring.springboot.domain 包里面的城市實(shí)體對(duì)象類。城市(City)對(duì)象 City,代碼如下:
import org.springframework.data.annotation.Id;
import java.io.Serializable;
/**
* 城市實(shí)體類
*
*/
public class City implements Serializable {
private static final long serialVersionUID = -2081742442561524068L;
/**
* 城市編號(hào)
*/
@Id
private Long id;
/**
* 省份編號(hào)
*/
private Long provinceId;
/**
* 城市名稱
*/
private String cityName;
/**
* 描述
*/
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProvinceId() {
return provinceId;
}
public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
值得注意點(diǎn):
@Id 注解標(biāo)記對(duì)應(yīng)庫表的主鍵或者唯一標(biāo)識(shí)符。因?yàn)檫@個(gè)是我們的 DO ,數(shù)據(jù)訪問對(duì)象一一映射到數(shù)據(jù)存儲(chǔ)。
City 必須實(shí)現(xiàn)序列化,因?yàn)樾枰獙?duì)象序列化后存儲(chǔ)到 Redis。如果沒實(shí)現(xiàn) Serializable ,會(huì)引出異常:java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type
如果不是用默認(rèn)的序列化,需要自定義序列化實(shí)現(xiàn),只要實(shí)現(xiàn) RedisSerializer 接口去實(shí)現(xiàn)即可,然后在使用 RedisTemplate.setValueSerializer 方法去設(shè)置你實(shí)現(xiàn)的序列化實(shí)現(xiàn)。支持 JSON、XML 等。
控制層 CityWebFluxController
代碼如下:
import org.spring.springboot.domain.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping(value = "/city")
public class CityWebFluxController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping(value = "/{id}")
public Mono findCityById(@PathVariable("id") Long id) {
String key = "city_" + id;
ValueOperations
operations = redisTemplate.opsForValue(); boolean hasKey = redisTemplate.hasKey(key); City city = operations.get(key);
if (!hasKey) {
return Mono.create(monoSink -> monoSink.success(null)); }
return Mono.create(monoSink -> monoSink.success(city)); } @PostMapping() public Mono saveCity(@RequestBody City city) { String key =
"city_" + city.getId(); ValueOperations
operations = redisTemplate.opsForValue(); operations.set(key, city, 60, TimeUnit.SECONDS);
return Mono.create(monoSink -> monoSink.success(city)); } @DeleteMapping(value =
"/{id}") public Mono deleteCity(@PathVariable(
"id") Long id) { String key =
"city_" + id; boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) { redisTemplate.delete(key); }
return Mono.create(monoSink -> monoSink.success(id)); } }
使用 @Autowired 注入 RedisTemplate 對(duì)象。這個(gè)對(duì)象和 Spring 的 JdbcTemplate 功能十分相似,RedisTemplate 封裝了 RedisConnection,具有連接管理、序列化和各個(gè)操作等。還有針對(duì) String 的支持對(duì)象 StringRedisTemplate。
刪除 Redis 某對(duì)象,直接通過 key 值調(diào)用 delete(key)。
Redis 操作視圖接口類用的是 ValueOperations,對(duì)應(yīng)的是 Redis String/Value 操作。get 是獲取數(shù)據(jù);set 是插入數(shù)據(jù),可以設(shè)置失效時(shí)間。這里設(shè)置的失效時(shí)間是 60 s。
還有其他的操作視圖,ListOperations、SetOperations、ZSetOperations 和 HashOperations 。
運(yùn)行工程
一個(gè)操作 Redis 工程就開發(fā)完畢了,下面運(yùn)行工程驗(yàn)證下。使用 IDEA 右側(cè)工具欄,點(diǎn)擊 Maven Project Tab ,點(diǎn)擊使用下 Maven 插件的 install 命令?;蛘呤褂妹钚械男问?,在工程根目錄下,執(zhí)行 Maven 清理和安裝工程的指令:
cd springboot-webflux-6-redis
mvn clean install
在控制臺(tái)中看到成功的輸出:
... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2018-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------
在 IDEA 中執(zhí)行 Application 類啟動(dòng),任意正常模式或者 Debug 模式。可以在控制臺(tái)看到成功運(yùn)行的輸出:
... 省略
2018-04-10 08:43:39.932 INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935 INFO 2052 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-04-10 08:43:39.960 INFO 2052 --- [ main] org.spring.springboot.Application : Started Application in 6.547 seconds (JVM running for 9.851)
打開 POST MAN 工具,開發(fā)必備。進(jìn)行下面操作:
新增城市信息 POST http://127.0.0.1:8080/city
獲取城市信息 GET http://127.0.0.1:8080/city/2
如果等待 60s 以后,再次則會(huì)獲取為空。因?yàn)楸4娴臅r(shí)候設(shè)置了失效時(shí)間是 60 s。
當(dāng)前標(biāo)題:使用WebFlux集成Redis,SpringBoot2
網(wǎng)站鏈接:http://fisionsoft.com.cn/article/dpjhhji.html


咨詢
建站咨詢
