初学Redis的时候,利用Spring提供的Redis模板(StringRedisTemplate),操作本地Redis数据。
在这里分享给大家,有不足的地方,欢迎指正。
前提:搭建Spring环境,引入基本jar(这里不再描述),我自己搭建的是maven项目,故在pom.xml文件中引入以下dependency,因为其他地方也要用到别的jar,所以这里把Spring基本jar包全都引进来。
<properties>
<version.springframework>4.1.5.RELEASE</version.springframework>
<version.framework.core>0.0.34</version.framework.core>
</properties>
<dependencies>
<!--SpringFramework 4.1.5.RELEASE -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${version.springframework}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${version.springframework}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${version.springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${version.springframework}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${version.springframework}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${version.springframework}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${version.springframework}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${version.springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${version.springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${version.springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${version.springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${version.springframework}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
第一步,配置Redis,我是在applicationContext.xml文件配置的(文件名自己定义)
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd ">
<context:component-scan base-package="redis" />
<!-- spring管理redis缓存管理器 -->
<bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
<constructor-arg index="0" ref="redisTemplate" />
</bean>
<cache:annotation-driven cache-manager="redisCacheManager" />
<!-- 引入redis配置 -->
<context:property-placeholder location="classpath:system.properties" ignore-unresolvable="true"/>
<!-- jedis 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<!-- redis的连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.ip}" />
<property name="port" value="${redis.port}"/>
<property name="password" value="${redis.auth}"/>
<property name="database" value="${redis.db}"/>
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- spring data 提供 redis模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
</bean>
</beans>
system.properties文件
redis.pool.maxTotal=105
redis.pool.maxIdle=10
redis.pool.maxWaitMillis=5000
redis.pool.testOnBorrow=true
redis.ip=127.0.0.1
redis.port=6379
redis.auth=myRedis
redis.db=1
第二步,编写Java代码,示例如下:
package redis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Spring测试类,要注意引用的jar包版本,不然会报错
*
* @author sunck
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:spring/applicationContext*.xml")
public class RedisTemplateHelper
{
@Autowired
private RedisTemplate<String, String> redisTemplate;// 注入配置好的Redis模板
@Test
public void testStr()
{
// 通过模板,获取到String类型的redis对象
ValueOperations<String, String> redisStr = redisTemplate.opsForValue();
// 使用set方法,保存key和value的值
redisStr.set("ssss", "会不会乱码");
// 使用get(key)的方法获取到city对应的值
String city = redisStr.get("ssss");
System.out.println(city);
}
@Test
public void testList()
{
ListOperations<String, String> redisList = redisTemplate.opsForList();
redisList.leftPush("cities", "南京");
redisList.leftPush("cities", "北京");
redisList.leftPush("cities", "上海");
redisList.remove("cities", -2, "南京");
List<String> list = redisList.range("cities", 0, 10);
System.out.println(list);
}
@Test
public void testSet()
{
SetOperations<String, String> redisSet = redisTemplate.opsForSet();
String[] arr =
{
"java", "redis", "mongo", "kafka"
};
redisSet.add("lesson", arr);
Set<String> set = redisSet.members("lesson");
System.out.println(set);
}
@Test
public void testSortSet()
{
ZSetOperations<String, String> redisZSet = redisTemplate.opsForZSet();
redisZSet.add("week", "sun", 0);
redisZSet.add("week", "tus", 2);
redisZSet.add("week", "mon", 1);
redisZSet.add("week", "fri", 4);
redisZSet.add("week", "mon", 3);
Set<String> set = redisZSet.rangeByScore("week", 0, 10);
System.out.println(set);
}
@Test
public void testHash()
{
HashOperations<String, Object, Object> redisHash = redisTemplate.opsForHash();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "小孙");
map.put("age", "27");
map.put("height", "180");
redisHash.putAll("people", map);
Set<Object> keys = redisHash.keys("people");
for (Object key : keys)
{
Object value = redisHash.get("people", key);
System.out.println(key + ":" + value);
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext(
"classpath*:spring/applicationContext*.xml");
final RedisTemplate<String, String> redisTemplate = appCtx.getBean("redisTemplate", RedisTemplate.class);
// 通过模板,获取到String类型的redis对象
ValueOperations<String, String> redisStr = redisTemplate.opsForValue();
// 使用set方法,保存key和value的值
redisStr.set("city", "南京");
// 使用get(key)的方法获取到city对应的值
String city = redisStr.get("city");
System.out.println(city);
}
}
注意:运行main方法之前,必须要先启动本地Redis,运行命令见前面的文章(Redis学习笔记),这里不再说明。
参考资料请看Redis官网
网友评论