JAVA中使用Redis

  上节讲解了如何在 centos 上安装 redis,点击查看。本节我们学习在 java 中使用 redis。需要将 jedis-*.jar 添加到 classpath(点击下载),如果使用连接池还需要 commons-pool-*.jar(点击下载) 添加到 classpath, 文章的附件中可供大家下载。

public class Test {
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) {
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
        </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">连接本地的 Redis 服务</span>
        Jedis jedis = <span style="color: rgba(0, 0, 255, 1)">new</span> Jedis("你的redis服务id"<span style="color: rgba(0, 0, 0, 1)">);
        System.out.println(</span>"Connection to server sucessfully"<span style="color: rgba(0, 0, 0, 1)">);
        </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">存储key为blog的数据至redis</span>
        jedis.set("blog", "http://www.cnblogs.com/myzhijie"<span style="color: rgba(0, 0, 0, 1)">);
        </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">读取出来,执行结果:</span><span style="color: rgba(0, 128, 0, 1); text-decoration: underline">http://www.cnblogs.com/myzhijie</span>
        System.out.println(jedis.get("blog"<span style="color: rgba(0, 0, 0, 1)">));
    } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception e) {
        e.printStackTrace();
    }
}

}

如果连接不上,请查看 redis 服务器端口是否打开,可以在本地使用 telnet 命令检查。