1.spring-data-redis如何连接到redis服务端
其中定义了两个接口 org.springframework.data.redis.connection下的RedisConnection和RedisConnectionFactory工厂接口:
public interface RedisConnection extends RedisCommands {
void close() throws DataAccessException;
boolean isClosed();
Object getNativeConnection();
boolean isQueueing();
boolean isPipelined();
void openPipeline();
List
public interface RedisConnectionFactory extends PersistenceExceptionTranslator {
RedisConnection getConnection();
}
RedisConnectionFactory接口只定义一个获取连接的方法,而PersistenceExceptionTranslator定义了出现异常时把异常转化为spring通用的DataAccessException异常,可以供spring统一处理。
spring-data-redis通过三种方式连接:
public class Example {
// inject the actual template
@Autowired
private RedisTemplate template;
// inject the template as ListOperations
@Autowired
private ListOperations listOps;
public void addLink(String userId, URL url) {
listOps.leftPush(userId, url.toExternalForm());
}
}
2.序列化
通过序列化接口org.springframework.data.redis.serializer来定制自己的序列化逻辑
public interface RedisSerializer {
/**
* Serialize the given object to binary data.
*
* @param t object to serialize
* @return the equivalent binary data
*/
byte[] serialize(T t) throws SerializationException;
/**
* Deserialize an object from the given binary data.
*
* @param bytes object binary representation
* @return the equivalent object instance
*/
T deserialize(byte[] bytes) throws SerializationException;
}
存到redis上都是二进制的值,现在spring-data-redis里面已经提供了几种序列化机制:
JacksonJsonRedisSerializer json格式序列化
JdkSerializationRedisSerializer jdk的序列化
OxmSerializer spring的orm的序列化
StringRedisSerializer 简单的字符串跟字节转换序列化
3.spring-data-redis的消息发布订阅处理
每次接收到消息,就会调用注册的listener来处理。
4.支持spring cache的处理抽象
这样支持在本地缓存访问过的记录。
5.访问redis时支持回调,给程序员开发充分的扩展性灵活性来处理自定义的一些操作
通过扩展回调接口:
public interface RedisCallback {
/**
* Gets called by {@link RedisTemplate} with an active Redis connection. Does not need to care about activating or
* closing the connection or handling exceptions.
*
* @param connection active Redis connection
* @return a result object or {@code null} if none
* @throws DataAccessException
*/
T doInRedis(RedisConnection connection) throws DataAccessException;
}
public List