撒子是jedis?
jedies是Redis官方推荐的java连接开发工具。使用Java操作Redis的中间件。
使用:
我们先在windows上下载Redis测试:https://github.com/microsoftarchive/redis/releases/tag/win-3.2.100
在运行的时候要打开redis-server.exe和redis-cli.exe。
1、导入对应的依赖
<!--jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
2、编码测试
新建一个空的项目就行,然后新建一个类测试。
- 连接数据库
- 操作命令
- 断开连接
package com.lyr;
import redis.clients.jedis.Jedis;
public class TestJedis {
public static void main(String[] args) {
//new Jedis 对象
Jedis jedis = new Jedis("127.0.0.1",6379);
System.out.println(jedis.ping());
}
}
结果:
jedis中的事务
package com.lyr;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestJedis {
public static void main(String[] args) {
//new Jedis 对象
Jedis jedis = new Jedis("127.0.0.1",6379);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","lyr");
jsonObject.put("age","18");
//开启事务
Transaction multi = jedis.multi();
String result = jsonObject.toJSONString();
try {
multi.set("user1",result);
multi.set("user2",result);
multi.exec(); //执行事务
}catch (Exception e){
multi.discard(); //放弃事务
e.printStackTrace();
}finally {
System.out.println(jedis.get("user1"));
System.out.println(jedis.get("user2"));
jedis.close(); //关闭连接
}
}
}
结果:
整合SpringBoot
在SpringBoot2.x之后,原来使用的jedis被替换为了lettuce
jedis:采用直连,多个线程操作的话是不安全的,如果想避免不安全的,使用jedis pool连接池,更像BIO模式。
lettuce:采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据,更像NIO模式。
步骤:
首先新建一个springboot项目
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置
在application.properties中配置redis的信息
#配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
3、测试
package com.lyr;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class SpringbootRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
//redisTemplate 操作不同的数据类型,api和之前的指令是一样的
//opsForValue 操作字符串 类似String
//opsForList 操作List 类似List
//opsForSet
//opsForHash
//opsForZset
//opsForGeo
//opsForHyperLogLog
redisTemplate.opsForValue().set("name","lyr");
System.out.println(redisTemplate.opsForValue().get("name"));
}
}
结果: