Spring boot 连接Redis实现HMSET操作
这篇文章记录使用spring-boot-starter-redis访问Redis。Redis相关的的配置文件放在Resources目录下的application.yml文件中,如下所示:
spring:
profiles: dev,default,test
redis:
database: 1
host: 192.168.107.253 #redis test server
port: 6379
首先在pom.xml中添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
RedisTemplate配置
Spring boot默认能够使用 @Autowired 注入RedisTemplate<String, String>,但是我的需求是使用HMSET来操作Redis,访问Redis的模板类型为:RedisTemplate<String, Map<String, String>>,因此使用一个配置类进行配置。
创建JedisConnectionFactory
默认情况下,Spring boot就会为Redis注入默认值,如下图所示:
由于实际部署的Redis的主机、端口、数据库ID在application.yml配置文件中,因此使用 @Value 注入相应的值,
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int databaseId;
然后在Jedis连接工厂时,主机、端口、数据库ID set进去即可。
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
factory.setHostName(host);
factory.setPort(port);
factory.setDatabase(databaseId);
logger.info("host:{}, port:{}, database:{}", factory.getHostName(),factory.getPort(), factory.getDatabase());
return factory;
}
RedisTemplate创建需要传入JedisConnectionFactory,然后设置对象的序列化格式,如果未正确设置序列化格式,可能会导致写入的数据乱码
配置类使用 @Configuration 标识,整个类完整代码如下:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Map;
/**
* Created by Administrator on 2018/4/9.
*/
@Configuration
public class LoginMacRedisConfig {
private static final Logger logger = LoggerFactory.getLogger(LoginMacRedisConfig.class);
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int databaseId;
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisPoolConfig getRedisConfig() {
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
factory.setHostName(host);
factory.setPort(port);
factory.setDatabase(databaseId);
logger.info("host:{}, port:{}, database:{}", factory.getHostName(),factory.getPort(), factory.getDatabase());
return factory;
}
@Bean
public RedisTemplate<String, Map<String, String>> redisTemplate() {
final RedisTemplate<String, Map<String, String>> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(stringRedisSerializer);
return template;
}
}
这样,我们就可以在其他类( @Service )中使用 @Autowired 注入RedisTemplate<String, Map<String, String>>了。这篇文章讨论了如何注入各种泛型的RedisTemplate。
@Autowired
private RedisTemplate<String, Map<String, String>> hmsetTemplate;
有个时候,我们需要在一个Spring Boot Application中使用多个RedisTemplate,可参考:[How to create a second RedisTemplate instance in a Spring Boot application
RedisTemplate HMSET操作
HMSET key field value [field value ...]
HMSET接受一个key,然后可以存储多个 field value。
Map<String, String> results = new HashMap<>();
results.put("mac_addr", mac);
results.put("cli_verstr", cli_verstr);
hmsetTemplate.opsForHash().putAll(uid, results);
具体完整代码以后再补充。
写入Redis成功后,连接redis查看最终结果:
redis-cli -h 192.168.107.253 -p 6379
redis 192.168.107.253:6379[1]> KEYS *
1) "1097672"
2) "1210073"
3) "162284"
redis 192.168.107.253:6379[1]> HGET 1097672 mac_addr
"7893f695112c465"
redis 192.168.107.253:6379[1]> HGET 1097672623 cli_verstr
"2.8"
Spring boot 连接Redis实现HMSET操作的更多相关文章
- Spring Boot 整合 Redis 实现缓存操作
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 ...
- spring boot 2.x 系列 —— spring boot 整合 redis
文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...
- Spring Boot 之 Redis详解
Redis是目前业界使用最广泛的内存数据存储. Redis支持丰富的数据结构,同时支持数据持久化. Redis还提供一些类数据库的特性,比如事务,HA,主从库. REmote DIctionary S ...
- Spring Boot + Mybatis + Redis二级缓存开发指南
Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...
- spring boot 结合Redis 实现工具类
自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...
- Spring Boot 2.X(六):Spring Boot 集成Redis
Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...
- Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis
在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...
- 【redis】spring boot利用redis的Keyspace Notifications实现消息通知
前言 需求:当redis中的某个key失效的时候,把失效时的value写入数据库. github: https://github.com/vergilyn/RedisSamples 1.修改redis ...
- spring boot 连接Mysql介绍
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
随机推荐
- rt-thread中动态内存分配之小内存管理模块方法的一点理解
@2019-01-18 [小记] rt-thread中动态内存分配之小内存管理模块方法的一点理解 > 内存初始化后的布局示意 lfree指向内存空闲区首地址 /** * @ingroup Sys ...
- js日期格式转换的相关问题探讨
探讨问题1: 如何将 2017年8月22日 转换成 2017-8-22 / 2017-08-22呢 '2017年8月22日'.replace(/[年月日]/g,'-'); '2017年8月22日'.m ...
- js 获取当前时间 年月日
var datetime = new Date(); var year = datetime.getFullYear(); var month = datetime.getMonth() + 1 &l ...
- Docker中如何删除image(镜像)
原文地址:http://yaxin-cn.github.io/Docker/how-to-delete-a-docker-image.html docker中删除images的命令是docker rm ...
- function call操作符(operator()) 仿函数(functor)
主要是需要某种特殊的东西来代表一整组操作 代表一整组操作的当然是函数,过去通过函数指针实现 所以STL算法的特殊版本所接受的所谓条件或策略或一整组操作都以仿函数的形式呈现 #include <i ...
- JS实现选择排序
function selectSort(arr){ var len=arr.length; var temp; for(var i=0;i<len-1;i++){ for(var j=i+1;j ...
- JavaBean+Servlet 开发时,JavaBean 编写问题
在开发 JavaBean 时,遇见一个问题: ***** 表单字段为空,提交时出现 nullPointerException 异常: 表单字段不为空,提交正常. 使用 JavaBean ,JSP页 ...
- 使用postman测试hystrix
当在浏览器发送多次请求检测hystrix的作用时,我们可以使用postman来自动发送多次请求: 1.将链接保存到一个collection中 2.点击runner 3.设定运行次数
- SpringCloud之Hystrix断路器以及dashboard 属性详解
1.自定义hystrixCommand: https://blog.csdn.net/u012702547/article/details/78032191?utm_source=tuicool&am ...
- socket关闭状态问题
下面是对 譬如 “CLOSE_WAIT” 现象的一些解释: 主动关闭方和被动方经历的状态:FIN_WAIT_1(主动关闭一方): 当SOCKET在ESTABLISHED状态时,它想主动关 闭 ...