撒子是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"));
}
}
結果: