Redis入门实例(Redis+Sprint+maven创建工程)

时间:2023-11-10 16:19:50

一.>创建一个maven工程应用和相关配置:Redis_study,创建工程应用过程略

1.>配置pom.xml:文件内容如下

<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>Redis_dom1</groupId>
<artifactId>Redis_study</artifactId>
<version>01</version>
<packaging>war</packaging>
<name>Redis_study xzh</name> <build>
<!-- ###########给出构建过程中所用到的插件start######## -->
<plugins>
<!-- 由于maven默认使用的jdk与工程配置的jdk版本不一致,导致无法编译通过,通过该插件指定jdk版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- maven-surefire-plugin 是maven里执行测试用例的插件,不显示配置就会用默认配置。这个插件的 surefire:test 命令会默认绑定maven执行的 test 阶段 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- 跳过测试单元 true:跳过测试,false不跳过(默认)-->
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<!-- ###########给出构建过程中所用到的插件end######## -->
</build> <properties>
<spring.version>3.2.3.RELEASE</spring.version>
</properties> <dependencies>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> <!-- Redis客户端jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.0</version>
</dependency> <!-- spring-data-redis依赖 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.5.0.RELEASE</version>
</dependency> <!-- spring相关 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>

2.>配置Redis属性文件redis.properties:文件内容如下

#redis.hostName=localhost
#配置服务器ip地址
redis.hostName=***.***.***.**
redis.port=6379
redis.password=redisroot
redis.timeout=5000
redis.pool.maxActive=200
redis.pool.maxIdle=50
redis.pool.minIdle=20
redis.pool.maxWait=3000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.pool.usePool=true

3.>配置Spring启动需初始化的上下文bean:application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--使用注解 -->
<context:annotation-config /> <!-- 加载redis配置文件 -->
<context:property-placeholder location="classpath:redis.properties" />
<bean id="jedisPoolConfig1" class="redis.clients.jedis.JedisPoolConfig">
</bean> <!-- ################RedisTemplate操作模板配置begin##################### -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="hostName" value="${redis.hostName}"></property>
<property name="port" value="${redis.port}"></property>
<property name="password" value="${redis.password}"></property>
<property name="timeout" value="${redis.timeout}"></property>
<property name="usePool" value="${redis.pool.usePool}"></property>
<property name="poolConfig" ref="jedisPoolConfig1"></property>
</bean> <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
<!-- ################RedisTemplate操作模板配置end##################### --> <!-- ################JedisPool操作配置begin ##############################-->
<!-- Redis连接池的配置 -->
<bean id="jedisPoolConfig2" class="redis.clients.jedis.JedisPoolConfig" >
<property name="maxTotal" value="${redis.pool.maxActive}"/> <!-- 控制一个pool可分配多少个jedis实例 -->
<property name="maxIdle" value="${redis.pool.maxIdle}"/> <!-- 控制一个pool最多有多少个状态为idle(空闲)的jedis实例 -->
<property name="minIdle" value="${redis.pool.minIdle}"/> <!-- 控制一个pool最少有多少个状态为idle(空闲)的jedis实例 -->
<property name="maxWaitMillis" value="${redis.pool.maxWait}"/><!-- 表示当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException -->
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/><!-- 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 -->
<property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig2"/>
<constructor-arg index="1" value="${redis.hostName}" />
<constructor-arg index="2" value="${redis.port}" />
<constructor-arg index="3" value="${redis.timeout}" />
<!--Redis密码-->
<constructor-arg index="4" value="${redis.password}" />
</bean>
<!-- ################JedisPool操作配置end ################################--> </beans>

二.>编写测试代码

1.>编写Spring单位测试加载基础类:BaseTest.java

package redis;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.ContextConfiguration;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//指定bean注入的配置文件
@ContextConfiguration(locations = {"classpath:application.xml"})
//使用标准的JUnit @RunWith 注释运行Spring Test Runner
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest extends AbstractJUnit4SpringContextTests {}

2.>编写测试类:RedisTest.java

package redis;
import java.util.concurrent.TimeUnit;
import java.util.Map;
import java.util.HashMap; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
*
* @ClassName: RedisTest
* @Description: TODO
* @author xzh
* @date 20170323
*
*/
public class RedisTest extends BaseTest
{
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private JedisPool jedisPool;
public Map<String,String> student = new HashMap<String,String>();
/**
* 测试插入与获取Redis的数据
* @Title: testPutAndGet
* @Description: TODO
* @throws
*/
@Test
public void testPutAndGet()
{
System.out.println(this.getClass().getName()+"testPutAndGet");
redisTemplate.opsForHash().put("user", "name", "rhwayfun");
Object object = redisTemplate.opsForHash().get("user", "name");
System.out.println(object);
}
/**
* 测试Redis作为缓存的例子
* @Title: testCache
* @Description: TODO
* @throws InterruptedException
* @throws
*/
@Test
public void testCache() throws InterruptedException
{
//-------jedisPool配置使用--redisTemplate--进行操作Start-------------//
System.out.println("-------jedisPool配置使用--redisTemplate--进行操作Start-------------");
// 插入一条数据
redisTemplate.opsForHash().put("user", "name", "rhwayfun");
// 设置失效时间为6秒
redisTemplate.expire("user", 6, TimeUnit.SECONDS);
// 3秒后获取
Thread.sleep(3000);
Object object = redisTemplate.opsForHash().get("user", "name");
System.out.println("3秒后:" + object);
// 7秒后获取
Thread.sleep(4000);
object = redisTemplate.opsForHash().get("user", "name");
System.out.println("7秒后:" + object);
System.out.println("-------jedisPool配置使用--redisTemplate--进行操作end---------------\n");
//-------jedisPool配置使用--redisTemplate--进行操作end-------------// //-------jedisPool配置使用----Jedis----进行操作Start-------------//
System.out.println("-------jedisPool配置使用Jedis的进行操作Start-------------");
Jedis jedis = jedisPool.getResource();
System.out.println("服务器IP地址:"+jedis.configGet("bind"));
/*hash api:hset*/
jedis.hset("me", "name", "xzh");
System.out.println("jedis.hset(me, name, xzh):" + jedis.hget("me", "name")); /*hash api:hmset*/
student.put("naem","xzh");
student.put("stid", "1");
jedis.hmset("student", student); //关闭连接
if(jedis != null)
{
student.clear();
jedisPool.close();
}
System.out.println("-------jedisPool配置使用Jedis的进行操作end--------------\n");
//-------jedisPool配置使用----Jedis----进行操作end-------------//
}
}

运行结果:运行之前先搭建号redis缓存服务,右键点击方法名,选择则“Run As”→“JUnit Test”即可

......
-------jedisPool配置使用--redisTemplate--进行操作Start-------------
3秒后:rhwayfun
7秒后:null
-------jedisPool配置使用--redisTemplate--进行操作end---------------

-------jedisPool配置使用Jedis的进行操作Start-------------
服务器IP地址:[bind, 127.0.0.1 192.168.248.85]
jedis.hset(me, name, xzh):xzh
-------jedisPool配置使用Jedis的进行操作end--------------

redis.RedisTesttestPutAndGet
rhwayfun

右键点击方法名,选择则“Run As”→“JUnit Test”即可