SpringBoot集成Redis
1 添加依赖
<!-- 加入redis支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2 添加配置信息
在application-dev.properties添加以下配置信息
# redis配置
spring.redis.host = localhost
spring.redis.port = 6379
spring.redis.password = 123456
在com.lening.config目录下,建立RedisConfig.java,内容如下:
package com.lening.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// redis序列化设置
RedisSerializer<?> redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
redisTemplate.setValueSerializer(redisSerializer);
redisTemplate.setHashValueSerializer(redisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
// factory.setPassword(password);
return factory;
}
}
3 redis操作测试
引入RedisTemplate进行redis的相关操作
@Autowired
private RedisTemplate<String, String> redisTemplate;
redis命令测试
3.1 set key value
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
opsForValue.set("mytime", "2020");
3.2 get key
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
String mytime = opsForValue.get("mytime");
3.3 incrby key number
ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
Long increment = opsForValue.increment("mytime", 500);
3.4 setnx key value
ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
Boolean setIfAbsent = opsForValue.setIfAbsent("mytime", "500");
3.5 expire
Boolean expire = redisTemplate.expire("mytime", 5, TimeUnit.SECONDS);
3.6 delete
redisTemplate.delete("mytime");