NoSQL学习:Redis与Spring集成:RedisTemplate

koushr 2018-10-04

NoSQL学习:Redis与Spring集成:RedisTemplate

1、Redis与Spring集成简介

通过此文,可以掌握如下功能点:1)spring和redis集成后,配置文件如何配置2)学会spring提供的直接操作redis的模板类RedisTemplate的常用操作,此模板类可以代替原来redis的自带的jedis的相关操作。RedisTemplate封装了很多redis的基本操作,使用起来更方便。

2、Redis与Spring集成的编码核心步骤

1)环境前期准备

2)创建基于maven的工程springredis

3)配置spring的spring-redis.xml文件主要包含如下几点:

  • 配置spring跟redis的集成信息
  • 配置redis的相关连接信息
  • 配置spring提供的模板类RedisTemplate的bean

4)创建测试类TestRedisTemplate,此测试类共展示了RedisTemplate对redis的key、hash、List、set、sortset等数据类型的基本插入和查询操作。

5)测试结果展示

3、Redis与Spring集成的具体编码

1)环境前期准备

已装好redis,参考之前的redis安装章节

2)创建基于maven的工程springredis

第一步:基于Maven创建工程springredis

第二步:配置工程依赖的jar包,在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.gongyunit</groupId>
 <artifactId>springredis</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 
 <name>springredis</name>
 <url>http://maven.apache.org</url>
 
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
 
 <dependencies>
 
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>4.2.8.RELEASE</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-redis</artifactId>
 <version>1.7.4.RELEASE</version>
 </dependency>
 
 <dependency> 
 <groupId>redis.clients</groupId> 
 <artifactId>jedis</artifactId> 
 <version>2.8.1</version> 
 </dependency> 
 
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 </dependencies>
</project>

3)配置spring的spring-redis.xml文件主要包含如下几点:

配置spring跟redis的集成信息

配置redis的相关连接信息

配置spring提供的模板类RedisTemplate的bean

具体操作如下:

第一步:创建文件夹src/main/resources

第二步:在该文件夹下创建包:config

第三步: 编写文件spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org
/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
 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
 http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
 http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
 default-autowire="byName" default-lazy-init="false">
 
 
 <!--读取properties配置文件,其它xml中可以用EL表达式直接获取key对应的value值-->
 <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.
PropertyPlaceholderConfigurer">
 <property name="ignoreUnresolvablePlaceholders" value="true" />
 <property name="searchSystemEnvironment" value="true" />
 <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
 <property name="locations">
 <list>
 <value>classpath*:all.properties</value>
 </list>
 </property>
 <property name="fileEncoding" value="GBK" />
 <property name="order" value="2" />
 </bean>
 
 
 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
 <property name="maxTotal" value="${redis.maxTotal}"></property>
 <property name="maxIdle" value="${redis.maxIdle}"></property>
 <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
 <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>
 <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>
 <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property>
 </bean>
 
<!-- redis服务器中心 -->
 <bean id="jedisConnectionFactory" 
class="org.springframework.data.redis.
connection.jedis.JedisConnectionFactory"> 
 <property name="poolConfig" ref="poolConfig" /> 
 <property name="port" value="${redis.port.read}" /> 
 <property name="hostName" value="${redis.ip.read}" /> 
 <property name="password" value="${redis.pwd}" /> 
 <property name="timeout" value="${redis.timeout.read}"></property> 
 </bean> 
 
 <bean id="redisTemplate"
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.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>

4)创建测试类TestRedisTemplate,

此测试类共展示了RedisTemplate对redis的key、hash、List、set、sortset等数据类型的基本插入和查询操作。

第一步:创建包:com.gy.springredis.test

第二步:创建类:TestRedisTemplate类:

package com.gy.springredis.test;
 
import java.util.HashMap;
import java.util.Map;
 
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;
 
public class TestRedisTemplate {
 public static void main(String[] args) {
 ClassPathXmlApplicationContext appCtx =
new ClassPathXmlApplicationContext("config/spring-redis.xml");
 final RedisTemplate<String, Object> redisTemplate = appCtx.getBean("redisTemplate",RedisTemplate.class);
 
//添加一个 key
 ValueOperations<String, Object> value = redisTemplate.opsForValue();
 value.set("tkey", "hello key");
 //获取 这个 key 的值
 System.out .println(value.get("tkey"));
 
 
 //添加 一个 hash集合
 HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
 Map<String,Object> map = new HashMap<String,Object>();
 map.put("name", "thashmap");
 map.put("age", "99");
 hash.putAll("thashmap", map);
//获取 map
 System.out .println(hash.entries("thashmap"));
 
 
 //添加 一个 list 列表
 ListOperations<String, Object> list = redisTemplate.opsForList();
 list.rightPush("tlist", "list1");
 list.rightPush("tlist", "list2");
//输出 list
 System.out .println(list.range("tlist", 0, 1));
 
 
 //添加 一个 set 集合
 SetOperations<String, Object> set = redisTemplate.opsForSet();
 set.add("tset", "set1");
 set.add("tset", "set2");
 set.add("tset", "set3");
//输出 set 集合
 System.out .println(set.members("tset"));
 
 
//添加有序的 set 集合
 ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
 zset.add("tzset", "zset1", 0);
 zset.add("tzset", "zset2", 1);
 zset.add("tzset", "zset3", 2);
//输出有序 set 集合
 System.out .println(zset.rangeByScore("tzset", 0, 2));
 }
}

5)测试结果展示

第一步:展示创建好的工程结构:

NoSQL学习:Redis与Spring集成:RedisTemplate

第二步:展示测试类的测试结果:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.hello key{age=99, name=thashmap}[list1, list2][set2, set3, set1][zset1, zset2, zset3]

相关推荐

DiamondTao / 0评论 2020-08-30