藉助Jedis能夠在Java上操做Redis。java
到https://mvnrepository.com/去找jar包下載便可。
若是是maven項目:redis
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
Jedis jedis = new Jedis('localhost'); jedis.auth(password); // 若是設置了密碼,就須要先執行AUTH命令,不然執行其餘操做會報錯
JedisPoo 類是Jedis的鏈接池,能夠用 GenericObjectPoolConfig 類來設置鏈接池,這裏我用了Spring。spring
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import javax.annotation.PostConstruct; /** * Created by fjh on 2017/6/15. */ @Component public class JedisUtils { private static JedisPool POOL; private static volatile boolean flag = false; @Value("${jedis.url:localhost}") private String url; @Value("${jedis.port:6379}") private int port; @Value("${jedis.timeout:1000}") private int timeOut; @Value("${jedis.auth}") private String auth; @Value("${jedis.pool.maxIdle:10}") private int maxIdle; @Value("${jedis.pool.maxTotal:100}") private int maxTotal; @Value("${jedis.pool.maxWaitMillis:10000}") private long maxWaitMillis; public static Jedis getResource() { return POOL.getResource(); } //帶有`@PostConstruct`註解的方法會在屬性注入以後執行 @PostConstruct private void init() { if (!flag) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(maxIdle); config.setMaxTotal(maxTotal); config.setMaxWaitMillis(maxWaitMillis); POOL = new JedisPool(config, url, port, timeOut, auth); flag = true; } } }
調用代碼:maven
Jedis jedis = null; try { jedis = JedisUtils.getResource(); System.out.println(jedis.keys("*")); } catch (Exception e) { e.printStackTrace(); } finally { if (jedis != null) jedis.close(); }