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 ...
随机推荐
- 【LOJ#6029】市场(线段树)
[LOJ#6029]市场(线段树) 题面 LOJ 题解 看着就是一个需要势能分析的线段树. 不难发现就是把第二个整除操作化为减法. 考虑一下什么时候整除操作才能变成减法. 假设两个数为\(a,b\). ...
- CANOE入门(三)
最好的学习方式是什么?模仿.有人会问,那不是山寨么?但是我认为,那是模仿的初级阶段,当把别人最好的设计已经融化到自己的血液里,变成自己的东西,而灵活运用的时候,才是真正高级阶段.正所谓画虎画皮难画骨. ...
- php记录
PHP反射API 反向代理使用https协议,后台Tomcat使用http,redirect时使用错误协议的解决办法 多记几个导出公式,手中有粮,心中不慌 哈哈哈 PhpExcel中文帮助手册 Php ...
- 假如你不小心干掉了系统,你该怎么办?(一次手贱的记录 ~ Ubuntu and Python3.6)
前言 多年未犯低级错误,今天犯了个不大不小的错误,记录下生活点滴吧 今天早上脑海里想了下,如果电脑挂了我要备份哪些东西?然后中午休息的时候就列了一下,没想到晚上就悲剧了... 这个是中午写的: ## ...
- CentOS安装Python3.7
vscode设置python3.7调试环境:https://www.cnblogs.com/dotnetcrazy/p/9095793.html 先下载一下压缩包(FTP传也一样):weget htt ...
- es6+的javascript拓展内容
一.let,const 1.因为块级的作用域,这样打印01234,循环外打印i会报错 for (let i = 0; i < 5; i++) { setTimeout(console.log(i ...
- chip
1.芯片(chip.pas/cpp) [问题描述] 企鹅集成电路公司生产了一种大小为 2×3的芯片.每块芯片是从一块大小为N×M的硅片上切下来的,但由于原材料纯度问题,因而有若干的单位正方形并不能作为 ...
- rabbitMQ使用一——helloworld
参考链接 :https://blog.csdn.net/zhulongxi/article/details/72867545 https://www.cnblogs.com/ericli-ericli ...
- JS实现clone()方法,对五种主要数据类型进行值复制
Object.Array.Boolean.Number.String 分为三种情况:普通变量,Array,Object 递归调用
- hystrix实战总结;
HystrixCircuitBreaker 有三种状态 : 断路器默认是20个请求失败才打开短路器,可以进行配置: CLOSED :关闭 OPEN :打开 HALF_OPEN :半开 1.接口正确,接 ...