Spring boot 链接Redis实现HMSET操做

这篇文章记录使用spring-boot-starter-redis访问Redis。Redis相关的的配置文件放在Resources目录下的application.yml文件中,以下所示:html

spring:
  profiles: dev,default,test
  redis:
    database: 1
    host: 192.168.107.253 #redis test server
    port: 6379

首先在pom.xml中添加依赖:java

<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>>,所以使用一个配置类进行配置。redis

建立JedisConnectionFactory

默认状况下,Spring boot就会为Redis注入默认值,以下图所示:spring

因为实际部署的Redis的主机、端口、数据库ID在application.yml配置文件中,所以使用 @Value 注入相应的值,shell

@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,而后设置对象的序列化格式,若是未正确设置序列化格式,可能会致使写入的数据乱码app

配置类使用 @Configuration 标识,整个类完整代码以下:spring-boot

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。ui

@Autowired
    private RedisTemplate<String, Map<String, String>> hmsetTemplate;

有个时候,咱们须要在一个Spring Boot Application中使用多个RedisTemplate,可参考:[How to create a second RedisTemplate instance in a Spring Boot applicationspa

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"
相关文章
相关标签/搜索