日本免费全黄少妇一区二区三区-高清无码一区二区三区四区-欧美中文字幕日韩在线观看-国产福利诱惑在线网站-国产中文字幕一区在线-亚洲欧美精品日韩一区-久久国产精品国产精品国产-国产精久久久久久一区二区三区-欧美亚洲国产精品久久久久

Spring Boot如何整合Redis( 二 )


06、由上圖可看到我們編寫(xiě)了一個(gè)post請(qǐng)求用于存儲(chǔ)字符串 , get請(qǐng)求用于取出字符串 。啟動(dòng)類(lèi)通過(guò)main方法啟動(dòng)應(yīng)用,接下來(lái)我們使用postman去模擬瀏覽器調(diào)用post和get請(qǐng)求,由下圖可以看到Redis存儲(chǔ)的數(shù)據(jù)成功被取出 。
07、接下來(lái)我們介紹Jedis,這是一個(gè)封裝了Redis的客戶端 , 在Spring Boot整合Redis的基礎(chǔ)上,可以提供更簡(jiǎn)單的API操作 。因此我們需要配置JedisPool的Bean , 代碼如下,其中@Configuration注解表明這是一個(gè)配置類(lèi),我們?cè)谠擃?lèi)中注入RedisProperties , 并且使用@Bean注解指定JedisPool 。
@Configuration
public class RedisConfiguration {

@Autowired
private RedisProperties properties;

@Bean
public JedisPool getJedisPool(){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(properties.getJedis().getPool().getMaxIdle());
config.setMaxTotal(properties.getJedis().getPool().getMaxActive());
config.setMaxWaitMillis(properties.getJedis().getPool().getMaxWait().toMillis());
JedisPool pool = new JedisPool(config,properties.getHost(),
properties.getPort(),100,
properties.getPassword(), properties.getDatabase());
return pool;
}
}
08、接下來(lái)我們編輯JedisUtil工具類(lèi),通過(guò)SpringBoot容器的@Component注解來(lái)自動(dòng)創(chuàng)建,并且注入JedisPool,使用jedisPool.getResource()方法來(lái)獲取Jedis , 并最終實(shí)現(xiàn)操作redis數(shù)據(jù)庫(kù),其代碼如下 。
@Component
public class JedisUtil {

@Autowired
JedisPool jedisPool;

//獲取key的value值
public String get(String key) {
Jedis jedis = jedisPool.getResource();
String str = "";
try {
str = jedis.get(key);
} finally {
try {
jedis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}

public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
String str = "";
try {
str = jedis.set(key, value);
} finally {
try {
jedis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}

}
09、JedisUtil工具類(lèi)編寫(xiě)完成后,我們修改之前的RedisController,并注入JedisUtil,代碼如下圖所示 。然后再用postman分別調(diào)用post和get接口,我們可以看到成功取到了新的key的value值 。
特別提示在Spring Boot整合Redis前本機(jī)需安裝Redis,另外可以使用RedisDesktopManager這個(gè)Redis這個(gè)桌面管理工具查看Redis中的數(shù)據(jù) 。

推薦閱讀