spring整合redis

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>com.shidebin.mongodb</groupId>
  <artifactId>spring-redis</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>spring-redis</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <!-- spring核心依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.3.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.3.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>4.3.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>4.3.3.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>4.3.3.RELEASE</version>
		</dependency>
		<!-- redis 相关-->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.6.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>
		<!-- json-->
	<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>
    <!-- 单元测试相关依赖 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.2.RELEASE</version>
			<scope>test</scope>
		</dependency>
  </dependencies>
</project>

applicationContext.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:c="http://www.springframework.org/schema/c"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:cache="http://www.springframework.org/schema/cache" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:redisson="http://redisson.org/schema/redisson"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
		                http://www.springframework.org/schema/context 
		                http://www.springframework.org/schema/context/spring-context-4.3.xsd
		                http://www.springframework.org/schema/cache
                        http://www.springframework.org/schema/cache/spring-cache.xsd
                        http://www.springframework.org/schema/tx 
          				http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
          				http://redisson.org/schema/redisson
          				http://redisson.org/schema/redisson/redisson.xsd">

                        

	<context:property-placeholder location="classpath:redis.properties"
		ignore-unresolvable="true" />


	<tx:annotation-driven /> 
	<context:component-scan base-package="com.james.cache.utils">
	</context:component-scan>
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="100" />
		<property name="maxIdle" value="10" />
	</bean>
	
	<bean id="jedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
		destroy-method="destroy">
		<property name="hostName" value="${redis.host}" />
		<property name="port" value="${redis.port}" />
		<property name="database" value="${redis.database}" />
		<property name="timeout" value="${redis.timeout}" />
		<property name="usePool" value="true" />
		<property name="password" value="${redis.password}"/>
		<property name="poolConfig" ref="jedisPoolConfig" />
	</bean>

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<property name="keySerializer" ref="stringRedisSerializer"/>
			 
		<property name="valueSerializer" ref="stringRedisSerializer"/>
		
		<property name="enableTransactionSupport" value="false"></property>
	</bean>
	<!-- String 数据类型 -->
	<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.DefaultValueOperations">
		<constructor-arg ref="redisTemplate"></constructor-arg>
	</bean>
	<!-- String 数据类型 -->
	<bean id="hashRedisTemplate" class="org.springframework.data.redis.core.DefaultHashOperations">
		<constructor-arg ref="redisTemplate"></constructor-arg>
	</bean>
	<!-- list 数据类型 -->
	<bean id="listRedisTemplate" class="org.springframework.data.redis.core.DefaultListOperations">
		<constructor-arg ref="redisTemplate"></constructor-arg>
	</bean>
	<!-- set 数据类型 -->
	<bean id="setRedisTemplate" class="org.springframework.data.redis.core.DefaultSetOperations">
		<constructor-arg ref="redisTemplate"></constructor-arg>
	</bean>
	<!-- zSet 数据类型 -->
	<bean id="zSetRedisTemplate" class="org.springframework.data.redis.core.DefaultZSetOperations">
		<constructor-arg ref="redisTemplate"></constructor-arg>
	</bean>
	
	
	
	<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
    <bean  id ="JdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>  
  
    <bean  id="GenericToStringSerializer" class="org.springframework.data.redis.serializer.GenericToStringSerializer"  
            c:type="java.lang.Long"/>  
	
	
    <cache:annotation-driven/>

	<!-- declare Redis Cache Manager -->
	<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
		<constructor-arg index="0" ref="redisTemplate"></constructor-arg>
	</bean>


</beans>

test类:

package com.shidebin.mongodb.spring_redis;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
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.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
	@Autowired
	public ValueOperations<String,String> stringRedisTemplate;
	@Autowired
	public HashOperations<String,String,String> hashRedisTemplate;
	@Autowired
	public ListOperations<String,String> listRedisTemplate;
	@Autowired
	public SetOperations<String,String> setRedisTemplate;
	@Autowired
	public ZSetOperations<String,String> zSetRedisTemplate;
	@Test
	public void set() {
		//set name shidebin
		stringRedisTemplate.set("name", "shidebin");	
		//保存对象
		User user = User.getUserBuilder().name("shidebin").age(29).sex("男").build();
		String jsonString = JSON.toJSONString(user);
		stringRedisTemplate.set("user:1", jsonString);
		//保存list
		List<String> list = new ArrayList<String>();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		String listJson = JSON.toJSONString(list);
		stringRedisTemplate.set("list", listJson);
		//保存map
		Map<String,String> map = new HashMap<String,String>();
		map.put("name", "shidebin");
		map.put("age", "29");
		map.put("phone", "18615412359");
		String mapJson = JSON.toJSONString(map);
		stringRedisTemplate.set("map", mapJson);
		//mset country china city beijing
		stringRedisTemplate.multiSet(map);
	}
	@SuppressWarnings("unchecked")
	@Test
	public void get() {
		//取string
		String name = stringRedisTemplate.get("name");
		System.out.println(name);
		//取对象
		String userStr = stringRedisTemplate.get("user:1");
		User parseObject = JSON.parseObject(userStr, User.class);
		System.out.println(userStr);
		System.out.println(parseObject);
		//取list
		String listStr = stringRedisTemplate.get("list");
		List<String> parseObject2 = JSON.parseArray(listStr, String.class);
		System.out.println(listStr);
		System.out.println(parseObject2);
		//取map
		String mapStr = stringRedisTemplate.get("map");
		Map<String,String> parseObject3 = JSON.parseObject(mapStr, Map.class);
		System.out.println(mapStr);
		System.out.println(parseObject3);
		//mget country city address
		List<String> multiGet = stringRedisTemplate.multiGet(Arrays.asList("name","age","phone"));
		System.out.println(multiGet);
	}
	//hash
	@Test
	public void hSet() {
		Map<String,String> map = new HashMap<String,String>();
		map.put("name", "shidebin");
		map.put("age", "29");
		map.put("phone", "18615412359");
		hashRedisTemplate.putAll("user:2", map);
	}
	@Test
	public void hGet() {
		Map<String, String> entries = hashRedisTemplate.entries("user:2");
		System.out.println(entries);
	}
	//list
	@Test
	public void lpush() {
		List<String> list = new ArrayList<String>();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		listRedisTemplate.leftPushAll("list:1", list);
	}
	@Test
	public void lget() {
		List<String> range = listRedisTemplate.range("list:1", 0, -1);
		System.out.println(range);
	}
	//list
		@Test
		public void sset() {
			List<String> list = new ArrayList<String>();
			list.add("aaa");
			list.add("bbb");
			list.add("ccc");
			setRedisTemplate.add("set:1", list.toArray(new String[] {}));
		}
		@Test
		public void sget() {
			Set<String> members = setRedisTemplate.members("set:1");
			System.out.println(members);
		}
		//list
		@Test
		public void zpush() {
			Set<TypedTuple<String>> set = new HashSet<TypedTuple<String>>();
			TypedTuple<String> tt = new DefaultTypedTuple<String>("shidebin",Double.valueOf(23));
			set.add(tt);
			zSetRedisTemplate.add("zset",set);
		}
		@Test
		public void zget() {
			Set<TypedTuple<String>> rangeWithScores = zSetRedisTemplate.rangeWithScores("zset", 0, -1);
			rangeWithScores.stream().forEach(action -> {
				System.out.println(action.getScore());
				System.out.println(action.getValue());
			});
		}
}

我使用是各数据类型注入的方式,需要什么数据类型就注入哪个接口,也可以直接使用spring提供的redisTemplate,但每次使用时都要调对应的bound方法,感觉有些冗余,直接在xml声明对应的数据类型的bean感觉更简洁。
git上工程路径:https://github.com/shidebin/redis

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值