java如何通过多线程从redis中获取数据
时间: 2023-06-27 22:02:38 浏览: 81
Java中可以通过Jedis库来操作Redis,下面是一个通过多线程从Redis中获取数据的示例代码:
```java
import redis.clients.jedis.Jedis;
public class RedisThread extends Thread {
private String key;
public RedisThread(String key) {
this.key = key;
}
@Override
public void run() {
Jedis jedis = new Jedis("localhost", 6379);
while (true) {
String value = jedis.get(key);
System.out.println(Thread.currentThread().getName() + " : " + value);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
RedisThread thread1 = new RedisThread("key1");
RedisThread thread2 = new RedisThread("key2");
RedisThread thread3 = new RedisThread("key3");
thread1.start();
thread2.start();
thread3.start();
}
}
```
在这个示例代码中,我们创建了一个`RedisThread`类,它继承自`Thread`类。在`run()`方法中,我们创建了一个Jedis实例,然后通过`get()`方法从Redis中获取指定的key的值,并输出到控制台上。
在`main()`方法中,我们创建了三个`RedisThread`线程,并启动它们。每个线程都会不断地从Redis中获取指定的key的值,并输出到控制台上。由于多个线程同时访问Redis,因此需要注意线程安全问题。