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中的数据 。
推荐阅读
- 如何使用SQL代码创建数据库
- 如何利用Python中的Pandas库绘制柱形图
- DEV c++ 如何进行程序调试
- sql server如何添加外键
- 如何定义和遍历二维数组java
- 如何在SPSS中对个案等级排序
- JedisConnectionFactory如何获取Redis
- CMD命令如何进入和退出一个文件夹
- Matlab如何生成随机矩阵
- 如何利用matlab画柱状图