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