Spring Boot and RESTful API(5)Redis

SpringBootandRESTfulAPI(5)Redis

RedisConnection

scanonlysupportedafter2.8.0

https://redis.io/commands/scan

Iamusing/opt/redis-2.6.14.IneedtoupdatemyRedisonlocalmachinefirst.

>wgethttp://download.redis.io/releases/redis-3.2.9.tar.gz

unzipthefileandbuildthebinary

>make

>mkdir/Users/carl/tool/redis-3.2.9

>mkdir/Users/carl/tool/redis-3.2.9/bin

>mkdir/Users/carl/tool/redis-3.2.9/conf

>cpsrc/redis-server/Users/carl/tool/redis-3.2.9/bin/

>cpsrc/redis-benchmark/Users/carl/tool/redis-3.2.9/bin/

>cpsrc/redis-cli/Users/carl/tool/redis-3.2.9/bin/

>cpredis.conf/Users/carl/tool/redis-3.2.9/conf/

StarttheServer

>nohupbin/redis-serverconf/redis.conf&

ConfigurationandCodeforSpringRedis

pom.xmltoincludethepackage

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

YAMLconfigurationfileapplication.yaml

spring:

profiles:

active:dev

redis:

database:0

host:localhost

port:6379

DirectlyhaveatestClassontheRedisTemplate,RedisTemplateTest.java

packagecom.sillycat.jobsmonitorapi.repository;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.context.SpringBootTest;

importorg.springframework.data.redis.core.Cursor;

importorg.springframework.data.redis.core.RedisTemplate;

importorg.springframework.data.redis.core.ScanOptions;

importorg.springframework.test.context.junit4.SpringRunner;

importorg.springframework.util.Assert;

@RunWith(SpringRunner.class)

@SpringBootTest

publicclassRedisTemplateTest{

@Autowired

RedisTemplate<String,String>redisTemplate;

@Test

publicvoidtestStringCRUD(){

Stringkey="language";

Stringvalue="java";

this.redisTemplate.opsForValue().set(key,value);

Stringresult1=redisTemplate.opsForValue().get(key);

Assert.isTrue(value.equals(result1),"WrongdatafromRedis");

this.redisTemplate.delete(key);

Stringresult2=redisTemplate.opsForValue().get(key);

Assert.isNull(result2,"DataisnotdeletedsuccessfullyfromRedis");

}

@Test

publicvoidtestScanning(){

this.redisTemplate.opsForValue().set("cache_geo_lat_long_info_by_zipcode_13434","1");

this.redisTemplate.opsForValue().set("cache_geo_lat_long_info_by_zipcode_12","2");

this.redisTemplate.opsForValue().set("cache_geo_lat_long_info_by_zipcode_1234","2");

Stringpattern="cache_geo_lat_long_info_by_zipcode_*";

ScanOptions.ScanOptionsBuilderscanOptionsBuilder=newScanOptions.ScanOptionsBuilder();

scanOptionsBuilder.match(pattern);

Cursor<byte[]>cursors=this.redisTemplate.getConnectionFactory().getConnection().scan(scanOptionsBuilder.build());

for(;cursors.hasNext();){

StringtempKey=newString(cursors.next());

if(tempKey.length()=="cache_geo_lat_long_info_by_zipcode_".length()+4){

System.out.println("findanddeleting----------------"+tempKey);

redisTemplate.delete(tempKey);

}

}

Stringresult1=redisTemplate.opsForValue().get("cache_geo_lat_long_info_by_zipcode_1234");

Assert.isNull(result1,"DataisnotdeletedsuccessfullyfromRedis");

}

}

SerializerObject

samplePOJO

package

com.sillycat.jobsmonitorapi.domain;

importjava.io.Serializable;

publicclassUserimplementsSerializable{

privatestaticfinallongserialVersionUID=-4062728253774262930L;

privateStringuserName;

privateIntegerage;

publicUser(StringuserName,Integerage){

this.userName=userName;

this.age=age;

}

..snip..getterandsetter

}

RedisHelper

packagecom.sillycat.jobsmonitorapi.repository;

importorg.springframework.core.convert.converter.Converter;

importorg.springframework.core.serializer.support.DeserializingConverter;

importorg.springframework.core.serializer.support.SerializingConverter;

importorg.springframework.data.redis.serializer.RedisSerializer;

importorg.springframework.data.redis.serializer.SerializationException;

publicclassRedisObjectSerializerimplementsRedisSerializer<Object>{

privateConverter<Object,byte[]>serializer=newSerializingConverter();

privateConverter<byte[],Object>deserializer=newDeserializingConverter();

staticfinalbyte[]EMPTY_ARRAY=newbyte[0];

publicObjectdeserialize(byte[]bytes){

if(isEmpty(bytes)){

returnnull;

}

try{

returndeserializer.convert(bytes);

}catch(Exceptionex){

thrownewSerializationException("Cannotdeserialize",ex);

}

}

publicbyte[]serialize(Objectobject){

if(object==null){

returnEMPTY_ARRAY;

}

try{

returnserializer.convert(object);

}catch(Exceptionex){

returnEMPTY_ARRAY;

}

}

privatebooleanisEmpty(byte[]data){

return(data==null||data.length==0);

}

}

RedisConfig

packagecom.sillycat.jobsmonitorapi.config;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importorg.springframework.data.redis.connection.RedisConnectionFactory;

importorg.springframework.data.redis.connection.jedis.JedisConnectionFactory;

importorg.springframework.data.redis.core.RedisTemplate;

importorg.springframework.data.redis.serializer.StringRedisSerializer;

importcom.sillycat.jobsmonitorapi.domain.User;

importcom.sillycat.jobsmonitorapi.repository.RedisObjectSerializer;

@Configuration

publicclassRedisConfig{

@Bean

JedisConnectionFactoryjedisConnectionFactory(){

returnnewJedisConnectionFactory();

}

@Bean

publicRedisTemplate<String,User>redisTemplate(RedisConnectionFactoryfactory){

RedisTemplate<String,User>template=newRedisTemplate<String,User>();

template.setConnectionFactory(jedisConnectionFactory());

template.setKeySerializer(newStringRedisSerializer());

template.setValueSerializer(newRedisObjectSerializer());

returntemplate;

}

}

ExtendtheTester

packagecom.sillycat.jobsmonitorapi.repository;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.context.SpringBootTest;

importorg.springframework.data.redis.core.Cursor;

importorg.springframework.data.redis.core.RedisTemplate;

importorg.springframework.data.redis.core.ScanOptions;

importorg.springframework.test.context.junit4.SpringRunner;

importorg.springframework.util.Assert;

importcom.sillycat.jobsmonitorapi.domain.User;

@RunWith(SpringRunner.class)

@SpringBootTest

publicclassRedisTemplateTest{

@Autowired

RedisTemplate<String,String>redisTemplateString;

@Autowired

RedisTemplate<String,User>redisTemplateUser;

@Test

publicvoidtestStringCRUD(){

Stringkey="language";

Stringvalue="java";

this.redisTemplateString.opsForValue().set(key,value);

Stringresult1=redisTemplateString.opsForValue().get(key);

Assert.isTrue(value.equals(result1),"WrongdatafromRedis");

this.redisTemplateString.delete(key);

Stringresult2=redisTemplateString.opsForValue().get(key);

Assert.isNull(result2,"DataisnotdeletedsuccessfullyfromRedis");

}

@Test

publicvoidtestScanning(){

this.redisTemplateString.opsForValue().set("cache_geo_lat_long_info_by_zipcode_13434","1");

this.redisTemplateString.opsForValue().set("cache_geo_lat_long_info_by_zipcode_12","2");

this.redisTemplateString.opsForValue().set("cache_geo_lat_long_info_by_zipcode_1234","2");

Stringpattern="cache_geo_lat_long_info_by_zipcode_*";

ScanOptions.ScanOptionsBuilderscanOptionsBuilder=newScanOptions.ScanOptionsBuilder();

scanOptionsBuilder.match(pattern);

Cursor<byte[]>cursors=this.redisTemplateString.getConnectionFactory().getConnection()

.scan(scanOptionsBuilder.build());

for(;cursors.hasNext();){

StringtempKey=newString(cursors.next());

if(tempKey.length()=="cache_geo_lat_long_info_by_zipcode_".length()+4){

redisTemplateString.delete(tempKey);

}

}

Stringresult1=redisTemplateString.opsForValue().get("cache_geo_lat_long_info_by_zipcode_1234");

Assert.isNull(result1,"DataisnotdeletedsuccessfullyfromRedis");

}

@Test

publicvoidtestObjectUser(){

Useruser1=newUser("sillycat",35);

redisTemplateUser.opsForValue().set(user1.getUserName(),user1);

Useruser2=newUser("kiko",30);

redisTemplateUser.opsForValue().set(user2.getUserName(),user2);

Assert.isTrue(redisTemplateUser.opsForValue().get(user1.getUserName()).getAge().equals(user1.getAge()),

"agenotequal");

Assert.isTrue(

redisTemplateUser.opsForValue().get(user2.getUserName()).getUserName().equals(user2.getUserName()),

"usernamenotequal");

}

}

BeanMapping

http://orika-mapper.github.io/orika-docs/intro.html

Learnfromorg.springside.modules.utils.mapper.BeanMapper

References:

https://stackoverflow.com/questions/17162725/spring-data-redis-redistemplate-exception/30484834#30484834

http://blog.didispace.com/springbootredis/

http://docs.spring.io/spring-data/redis/docs/1.6.2.RELEASE/reference/html/

相关推荐