spring data redis 操作redis

本文介绍了如何使用Spring Data Redis集成Jedis来操作Redis数据,并展示了与Spring MVC的简单整合,实现了用户添加和查询功能。提供了工程的下载链接以供进一步扩展。
摘要由CSDN通过智能技术生成

这篇文章主要说spring data redis 集成jedis操作 redis中的数据。

还有一个和spring mvc 的小整合。实现了对用户的添加查询操作,后期有需要大家可以自己扩展。

代码目录结构如下


下面列出几个主要的文件吧,最后面有整个工程的下载

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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.lzg</groupId>
	<artifactId>sdrdemo</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>sdrdemo Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<org.springframework.version>4.1.6.RELEASE</org.springframework.version>
		<spring.version>4.1.6.RELEASE</spring.version>
	</properties>
	<dependencies>
		<!-- config junit jar -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<!-- config redis data and client jar -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.5.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.6.2</version>
		</dependency>

		<!-- config need jar -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>org.apache.geronimo.specs</groupId>
			<artifactId>geronimo-servlet_3.0_spec</artifactId>
			<version>1.0</version>
		</dependency>

		<!-- cofig spring jar -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc-portlet</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>sdrdemo</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd              
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
    
    <!-- 激活@Controller模式 -->
    <mvc:annotation-driven />
    
    <!-- 启动注解 -->
    <context:annotation-config />  
    
    <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="cn.lzg" />
    
    <!-- 引入redis属性配置文件 -->
    <import resource="redis-context.xml"/>

</beans>

redis-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-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
               ">

	<!-- 扫描 redis properties -->
	<context:property-placeholder location="classpath:property/redis.properties" />

 <!--  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
      p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:use-pool="true"/>
  redis template definition
  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnectionFactory"/> -->
	
	<bean id="jedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
		p:use-pool="true" />

	<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<!-- 如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast to String!!! -->
<!-- 		<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>

</beans>

JedisApiTest.java 这个类主要包含了对redis 几种数据类型的常见API操作(String,List,Set,SortSet,Hash)

package cn.lzg.sdrdemo.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
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.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

@Component
public class JedisApiTest {
	//这里别写泛型,因为StringRedisTemplate的源码是默 extends RedisTemplate<String, User> 你写泛型了就无法正确按照类型匹配了
	@Autowired
	private RedisTemplate stringRedisTemplate;	
	//这里为什么能这样注入,是利用了spring 的Editor特性,具体见下面博客
	//http://www.cnblogs.com/chanedi/p/4135303.html
	//当然spring data redis 的官网也推荐了这个用法,注意这个特性是在 spring 3.2.8以上才有的,以后写demo要注意官方文档的requrement的提示
	//http://docs.spring.io/spring-data/redis/docs/1.4.0.RELEASE/reference/html/#redis:template
	@Resource(name = "stringRedisTemplate")
	private ListOperations<String, String> listOps;

	@Resource(name = "stringRedisTemplate")
	private ValueOperations<String, String> valueOps;

	@Resource(name = "stringRedisTemplate")
	private HashOperations<String, String, Object> hashOps;

	@Resource(name = "stringRedisTemplate")
	private SetOperations<String, String> setOps;
	
	@Resource(name = "stringRedisTemplate")
	private ZSetOperations<String, String> ZSetOps;

	//redis命令速查表 http://doc.redisfans.com/
	
	//List的操作
	public void testListOps(){
		//List 其实是一个双向链表,从下面的代码就能看出来可以从两边进行push/pop操作
		stringRedisTemplate.delete("listTest");	//删除这个List
		//添加操作
		listOps.rightPush("listTest", "1");
		listOps.rightPush("listTest", "2");
		listOps.leftPush("listTest", "3");
		listOps.leftPush("listTest", "4");
		
		// 查看listTest这个List的值
		System.out.println(listOps.range("listTest", 0, -1));	//[4, 3, 1, 2]
		
		// 取左边第一个值
		System.out.println(listOps.leftPop("listTest"));	//4
		
		// 查看listTest这个List的值
		System.out.println(listOps.range("listTest", 0, -1));	//[3, 1, 2]
		
		//修改操作  将下标为1的值修改为 "set_1",(下标从0开始)
		listOps.set("listTest", 1, "set_1");
		System.out.println(listOps.range("listTest", 0, -1));	//[3, set_1, 2]
		
		//删除操作  将下标为1,值为 set_1的元素删除
		listOps.remove("listTest", 1, "set_1");	
		System.out.println(listOps.range("listTest", 0, -1));	//[3, 2]
	}
	
	//set的操作
	public void testSetOps(){
		//添加
		setOps.add("setTest1", "1","2","3","4");
		setOps.add("setTest2", "a","b","1","2");
		
		//查询 set集合是无序的
		System.out.println(setOps.members("setTest1"));//[2, 1, 3, 4]
		
		//判断是否有这个值
		System.out.println(setOps.isMember("setTest1", "4"));// true
		
		//删除  可以删除多个值
		setOps.remove("setTest1", "1","4");
		System.out.println(setOps.members("setTest1"));//[3, 2]
		
		//交集
		System.out.println(setOps.intersect("setTest1", "setTest2"));//[2]
		
		//并集
		System.out.println(setOps.union("setTest1", "setTest2"));//[d, 2, c, 1, a, 3, b]
		
		//差集
		System.out.println(setOps.difference("setTest1", "setTest2"));//[3]
	}

	// ZSetOps操作
	public void testZSetOps(){
		//添加
		ZSetOps.add("ZSetTest", "google.com", 10);
		ZSetOps.add("ZSetTest", "baidu.com", 8);
		ZSetOps.add("ZSetTest", "soso.com", 5);
		ZSetOps.add("ZSetTest", "360.com", 2);
		
		//默认按照分数的降序排列
		System.out.println(ZSetOps.range("ZSetTest", 0, -1));
		//[360.com, soso.com, baidu.com, google.com]
		
		//按照分数范围查询
		System.out.println(ZSetOps.rangeByScore("ZSetTest", 5, 10));
		//[soso.com, baidu.com, google.com]
		
		//查看排名
		System.out.println(ZSetOps.rank("ZSetTest", "baidu.com"));// 2  说明第一名是0
		
		// 按分数从大到小排列
		System.out.println(ZSetOps.reverseRange("ZSetTest", 0, -1));
		//[google.com, baidu.com, soso.com, 360.com]
		
		//看这个对象的 socre
		System.out.println(ZSetOps.score("ZSetTest", "google.com")); //10.0
		
		// 删除,按照对象
		ZSetOps.remove("ZSetTest", "360.com");
		// 删除,根据下标
		ZSetOps.removeRange("ZSetTest", 0, 1);
		// 删除,根据score
		ZSetOps.removeRangeByScore("ZSetTest", 2, 5);
	}
	
	// hash表操作 和Map差不多
	public void testHashOps(){
		// 添加
		hashOps.put("hashTest", "key1","aa");
		Map<String,String> map = new HashMap<String, String>();
		map.put("key2", "bb");
		map.put("key3", "cc");
		map.put("key4", "dd");
		hashOps.putAll("hashTest", map);
		
		// 查询所有的key
		System.out.println(hashOps.keys("hashTest")); //[key3, key4, key2, key1]
		
		//查询 所有的value
		System.out.println(hashOps.values("hashTest"));//[aa, bb, cc, dd]
		
		//删除 key
		hashOps.delete("hashTest", "key1");
		System.out.println(hashOps.keys("hashTest")); //[key2, key4, key3]
	}
	
	// String操作
	public void testValueOps(){
		valueOps.set("valueTest", "1");
		System.out.println(valueOps.get("valueTest"));
	}
}

上面代码直接跑junit的那个测试类就OK了。

集成spring mvc 的简单操作,大家可以下载工程后,直接部署去看下。

下载地址:http://download.csdn.net/detail/hunanlzg/9353113

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值