云服务器内容精选

  • 使用JedisPool访问(推荐) 样例代码 import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; public class JedisPoolTests { private static void testPool() { // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全; // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。 String pwd = System.getenv("EXAMPLE_PASSWORD_ENV"); JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "172.xx.xx.xx", 8635, 2000, pwd); Jedis jedis = pool.getResource(); try { System.out.println(jedis.hgetAll("676296")); System.out.println(jedis.set("key1", "value1")); } finally { jedis.close(); } pool.destroy(); } public static void main(String[] args) { testPool(); } }
  • 使用JedisCluster访问 样例代码 import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; public class ClusterTests { private static void testCluster() { String pwd = "a"; JedisCluster cluster = new JedisCluster(new HostAndPort("172.xx.xx.xx", 8635), 200, 2000, 5, pwd, new GenericObjectPoolConfig()); System.out.println(cluster.hgetAll("676296")); System.out.println(cluster.set("key1", "value1")); } public static void main(String[] args) { testCluster(); } }