Spring Boot如何整合Redis( 二 )


06、由上图可看到我们编写了一个post请求用于存储字符串 , get请求用于取出字符串 。启动类通过main方法启动应用,接下来我们使用postman去模拟浏览器调用post和get请求,由下图可以看到Redis存储的数据成功被取出 。
07、接下来我们介绍Jedis,这是一个封装了Redis的客户端 , 在Spring Boot整合Redis的基础上,可以提供更简单的API操作 。因此我们需要配置JedisPool的Bean , 代码如下,其中@Configuration注解表明这是一个配置类,我们在该类中注入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、接下来我们编辑JedisUtil工具类,通过SpringBoot容器的@Component注解来自动创建,并且注入JedisPool,使用jedisPool.getResource()方法来获取Jedis , 并最终实现操作redis数据库,其代码如下 。
@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工具类编写完成后,我们修改之前的RedisController,并注入JedisUtil,代码如下图所示 。然后再用postman分别调用post和get接口,我们可以看到成功取到了新的key的value值 。
特别提示在Spring Boot整合Redis前本机需安装Redis,另外可以使用RedisDesktopManager这个Redis这个桌面管理工具查看Redis中的数据 。

推荐阅读