JAVA语言之Spring boot 连接Redis实现HMSET操作
小标 2018-07-19 来源 : 阅读 1121 评论 0

摘要:本文主要向大家介绍了JAVA语言之Spring boot 连接Redis实现HMSET操作,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。

本文主要向大家介绍了JAVA语言之Spring boot 连接Redis实现HMSET操作,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。

这篇文章记录使用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

创建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. */

@Configurationpublic 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

    @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 6379redis 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"

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!


本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程