首先保证自己的服务器redis可以让外网访问。
1.在Spring Boot的pom文件引入redsi的启动器
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在配置文件Application.properties中添加配置
#redis
# Redis服务器地址
spring.redis.host=192.168.14.130
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
注意:如果用的是自己电脑的虚拟机那么如何找host?
使用ifconfig命令,inet 之后跟的ip地址即为host
3. 在Spring Boot中使用:
在Spring中有两个提供访问redis的类:
RedisTemplate<Object, Object>
StringRedisTemplate<String,String>和RedisTemplate其实一样,只是专门用来存取String类型的。
public class StringRedisTemplate extends RedisTemplate<String, String>
可以点击RedisTemplate的源码或是API来查看具体的方法。
@Autowired
StringRedisTemplate stringRedisTemplate;
//对应String类型
stringRedisTemplate.opsForValue();
//对应List类型
stringRedisTemplate.opsForList();
//散列类型
stringRedisTemplate.opsForHash();
//Set类型
stringRedisTemplate.opsForSet();
//有序集合
stringRedisTemplate.opsForZSet();
对于存储的序列化可以:
1. 自己用fastjion等序列化组件,将数据序列化后再利用StringRedisTemplate存储。
2. 自己写配置类,来配置自己想要的序列化方式。
使用:
直接在类中使用上述的RedisTemplate或是StringRedisTemplate
public class RedisServiceImpl{
//将放在容器中即可使用
@Autowired
private StringRedisTemplate stringRedisTemplate;
}