1.启动redis
2.导入坐标
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
3.做配置
spring:
data:
redis:
host: localhost
port: 6379
4.提供Redis接口对象RedisTemplate
ops*:获取各种类型数据接口
4.1操作字符串
@SpringBootTest
class Springboot02RedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void setage() {
ValueOperations ops = redisTemplate.opsForValue();
ops.set("age","17");
}
@Test
void getage() {
ValueOperations ops = redisTemplate.opsForValue();
System.out.println(ops.get("age"));
}
}
4.2操作哈希
@SpringBootTest
class Springboot02RedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void setage() {
HashOperations hash = redisTemplate.opsForHash();
hash.put("student","name","张三");
}
@Test
void getage() {
HashOperations hash = redisTemplate.opsForHash();
System.out.println(hash.get("student","name"));
}
}
5.Springboot读写redis的客户端
StringRedisTemplate
@SpringBootTest
class Springboot02RedisApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void getage() {
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
String age = stringStringValueOperations.get("age");
System.out.println(age);
}
}
6.Springboot操作redis客户端实现技术切换
spring:
data:
redis:
host: localhost
port: 6379
redis:
client-type: jedis
默认是lettuce(生菜)
lettuce(默认)和jsdis的区别
jedis链接redis服务器是直连模式,当多线程模式下使用jedis会存在线程安全问题,解决方案可以通过配置连接池使每个连接专用,这样整体性能就受很大影响。
lettcus基于netty框架进行与redis服务器连接,底层设计中采用statefulredisconnection。statefulredisconnection自身使线程安全的,可以保障并发访问安全问题,所以一个连接可以被多线程复用。当然lettcus也支持多线程实例一起工作。