這篇文章主要是要實現在項目中集成redis。
redis的安裝可以查看我的另一篇文章linux學習之centos7 安裝redis
1.引入redis依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
我的springboot版本用的是1.5.4.RELEASE
而redis最新是1.4.7.RELEASE:
Paste_Image.png
因此在pom代碼中設置了版本號
<version>1.3.2.RELEASE</version>
spring-boot-starter-redis給我們提供了RedisTemplate,方便我們對redis的配置和操作。
2.設置redis配置
在application.properties或者是yaml文件中設置:
# REDIS (RedisProperties)
# Redis數據庫索引(默認為0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器連接端口,生產服務端口要改,如果不改容易被感染 ,同時也最好設置好密碼
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=20000
注意
如果設置的密碼和redis中設置的不一樣會出現權限異常:
NOAUTH Authentication required.; nested exception is redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required."
我們可以在redis.conf
配置文件中找到requirepass
,這是redis訪問密碼設置的值。
3.讓spring 管理我們的RedisTemplate
創建RedisConfig,代碼如下:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
//使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
4.通過RedisTemplate 來操作我們的redis
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void t(){
ValueOperations valueOperations = redisTemplate.opsForValue();
SimpleLoginInfo simpleLoginInfo = SimpleLoginInfo.builder()
.gender(1).role(2).nickName("xiaohua").build();
//設置超時時間
valueOperations.set("xiaohua",simpleLoginInfo,2, TimeUnit.SECONDS);
//不設置超時
valueOperations.set("xiaoxiao",simpleLoginInfo);
SimpleLoginInfo xiaohua = (SimpleLoginInfo) valueOperations.get("xiaohua");
System.out.println(xiaohua.toString());
try{
Thread.sleep(3000);
SimpleLoginInfo xiaoxiao = (SimpleLoginInfo) valueOperations.get("xiaoxiao");
SimpleLoginInfo xiaohua2 = (SimpleLoginInfo) valueOperations.get("xiaohua");
System.out.println(xiaoxiao.toString());
System.out.println(xiaohua2.toString());
}catch (Exception e){
e.printStackTrace();
}
}
}
這樣我們的springboot就可以使用redis了。
總結:
本篇文章主要寫了springboot集成redis.而我們可以通過redis做很多事情,比如cache,key-value 保存等等..