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 ...
随机推荐
- Hdoj 1232.畅通工程 题解
Problem Description 某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇.省政府"畅通工程"的目标是使全省任何两个城镇间都可以实现交通 ...
- shell getopts用法
eg:sh test.sh -u tom -p 123456: getopts的使用形式:getopts OPTION_STRING VAR: OPTION_STRING:-u,-p这种自定义选项: ...
- 【BZOJ5323】[JXOI2018]游戏(组合计数,线性筛)
[BZOJ5323][JXOI2018]游戏(组合计数,线性筛) 题面 BZOJ 洛谷 题解 显然要考虑的位置只有那些在\([l,r]\)中不存在任意一个约数的数. 假设这样的数有\(x\)个,那么剩 ...
- 解决win10“cmd自动弹出一闪而过”问题的方法
1.禁用CMD win+Q gpedit 打开组策略 用户配置--管理模板--系统--阻止访问命令提示符--已启用. 2.启用PowerShell PS:需要使用CMD时可用powershell代替: ...
- [HAOI2015]树上染色(树形背包)
有一棵点数为 N 的树,树边有边权.给你一个在 0~ N 之内的正整数 K ,你要在这棵树中选择 K个点,将其染成黑色,并将其他 的N-K个点染成白色 . 将所有点染色后,你会获得黑点两两之间的距离加 ...
- web字体的设置
@font-face { font-family: 'OpenSans'; src: url("../fonts/open-sans-v15-latin-regular.woff2" ...
- 网络流24题 gay题报告
洛谷上面有一整套题. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 extra ①飞行员配对方案问题.top 裸二分图匹 ...
- openvpn部署账号密码登录
1.开启服务器端路由转发功能: 修改配置文件/etc/sysctl.conf中 net.ipv4.ip_forward = 0 改为 net.ipv4.ip_forward = 1 [root@nod ...
- Java 对远程文件的操作
首先添加jar <dependency> <groupId>jcifs</groupId> <artifactId>jcifs</artifact ...
- Python之函数--命名空间、作用域、global、nonlocal、函数的嵌套和作用域链
命名空间 -------‘’存放名字与值的关系”的空间 代码在运行伊始,创建的存储“变量名与值的关系”的空间叫做全局命名空间: 在函数的运行中开辟的临时的空间叫做局部命名空间. 命名空间一共分为三种: ...