这篇文章记录使用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操作的更多相关文章

  1. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!   『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』   本文提纲 ...

  2. spring boot 2.x 系列 —— spring boot 整合 redis

    文章目录 一.说明 1.1 项目结构 1.2 项目主要依赖 二.整合 Redis 2.1 在application.yml 中配置redis数据源 2.2 封装redis基本操作 2.3 redisT ...

  3. Spring Boot 之 Redis详解

    Redis是目前业界使用最广泛的内存数据存储. Redis支持丰富的数据结构,同时支持数据持久化. Redis还提供一些类数据库的特性,比如事务,HA,主从库. REmote DIctionary S ...

  4. Spring Boot + Mybatis + Redis二级缓存开发指南

    Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...

  5. spring boot 结合Redis 实现工具类

    自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...

  6. Spring Boot 2.X(六):Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

  7. Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis

    在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...

  8. 【redis】spring boot利用redis的Keyspace Notifications实现消息通知

    前言 需求:当redis中的某个key失效的时候,把失效时的value写入数据库. github: https://github.com/vergilyn/RedisSamples 1.修改redis ...

  9. spring boot 连接Mysql介绍

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

随机推荐

  1. Hdoj 2109.Fighting for HDU 题解

    Problem Description 在上一回,我们让你猜测海东集团用地的形状,你猜对了吗?不管结果如何,都没关系,下面我继续向大家讲解海东集团的发展情况: 在最初的两年里,HDU发展非常迅速,综合 ...

  2. Uva796 Critical Links

    用tarjan缩点 然后用dfn[u] < low[v]缩点并且保存起来 在sort一遍输出 #include<stdio.h> #include<string.h> # ...

  3. POJ-3687 Labeling Balls(拓扑)

    不一样的拓扑排序 给定一些标记为1到n的数, 求出满足a < b 的序列, 如果有多个输出, 按先标签1往前的位置, 然后按标签2往前的位置, 对于每个标签, 位置都尽量往前. 因为位置要往前, ...

  4. django rest framework ViewSets & Routers

    Using viewsets views.py from rest_framework import viewsets from rest_framework import mixins from r ...

  5. 20165223 《JAVA程序设计》第五周学习总结

    教材学习内容总结 第七章要点 内部类 匿名类 异常类 断言 第十章要点 File类 文件字节/字符的输入.输出流 缓冲流 随机流 数组流 数据流 对象流 序列化和对象克隆 使用Scanner解析文件 ...

  6. redis主从复制几种结构

    1.redis主从: 主从有好几种复制模式 一主一从:一个主服务器,一个从服务器,适合并发量较小的 一主多从:适合于读多写少的,结构: 3. 树状结构

  7. Typescript学习笔记(一)基础类型

    为了面向ng2和前端未来,开始搞向ts,ts是微软出的一枚语言,作为es6的超集,他出的一些特性还是蛮好用的(略坑).对于我等纯前端(从开始就接触javascript)的人来说,真想说,这特么什么鬼. ...

  8. Windows Update第三方工具概览

    受方程式黑客组织0Day攻击影响,所有的Windows服务器都要更新补丁. 方程式0day漏洞攻击介绍:https://zhuanlan.zhihu.com/p/26375989 腾讯云的解决方案:h ...

  9. An Introduction to OAuth 2

    PostedJuly 21, 2014 1.1mviews SECURITY API CONCEPTUAL Mitchell Anicas Introduction OAuth 2 is an aut ...

  10. Django(十一)请求生命周期之响应内容(请求/响应 头/体)

    https://www.cnblogs.com/renpingsheng/p/7534897.html Django请求生命周期之响应内容 http提交数据的方式有"post",& ...