3、redis之java client环境搭建
JAVA Client环境搭建
POM:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.1</version> </dependency>
非maven的可以去官网直接下载jar包
如果需要使用池需要用到common-pool,上面那个jedis的POM里已经包含了common-pool2-2.3.jar了,不需要再进行单独引用
common-pool2的POM:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.3</version> </dependency>
建立MAVEN项目
目录结构如下:
POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yzl</groupId> <artifactId>redis.first</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
RedisApp.java
package com.yzl;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
/**
* Reids之jedis的CRUD操作
*
* @author yangzhilong
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class RedisApp {
public Logger log = Logger.getLogger(this.getClass());
/**
*
* 功能描述: <br>
* CRUD操作之hello world
*
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public void crudFromRedisWidthSimple(){
Jedis jedis = new Jedis("127.0.0.1", 6379);
log.info("insert value to redis~~~");
jedis.set("name", "hello jedis");
log.info("get value from redis, value:" + jedis.get("name"));
log.info("delete key from redis~~~");
jedis.del("name");
log.info("get value from redis, value:" + jedis.get("name"));
jedis.close();
}
}
RedisAppTest.java
package com.yzl;
import org.junit.Test;
/**
* RedisApp的测试类
*
* @author yangzhilong
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class RedisAppTest {
@Test
public void crudFromRedisWidthSimpleTest(){
RedisApp app = new RedisApp();
app.crudFromRedisWidthSimple();
}
}
log4j.properties
### set log levels ###
log4j.rootLogger = debug , stdout
### \u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n
运行测试用例的结果:
2015-08-12 13:57:34,261 [com.yzl.RedisApp]-[INFO] insert value to redis~~~
2015-08-12 13:57:34,276 [com.yzl.RedisApp]-[INFO] get value from redis, value:hello jedis
2015-08-12 13:57:34,276 [com.yzl.RedisApp]-[INFO] delete key from redis~~~
2015-08-12 13:57:34,276 [com.yzl.RedisApp]-[INFO] get value from redis, value:null