spring+redis整合及操作

更新时间:2024-03-22 16:38:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Redis+Spring整合

前言

Redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

Redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部分场合可以对关系数据库起到很好的补充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端,使用很方便。

Redis支持主从同步。数据可以从主服务器向任意数量的从服务器上同步,从服务器可以是关联其他从服务器的主服务器。这使得Redis可执行单层树复制。存盘可以有意无意的对数据进行写操作。由于完全实现了发布/订阅机制,使得从数据库在任何地方同步树时,可订阅一个频道并接收主服务器完整的消息发布记录。同步对读取操作的可扩展性和数据冗余很有帮助。

redis的官网地redis.io

spring+redis集成实例

1. 所需jar文件

spring-data-redis-1.4.2.RELEASE.jar、jedis-2.5.2.jar 2. spring配置redis

我们需要创建一个新的CacheManager bean来管理redis缓存,Redis不是应用的共享内存,它只是一个内存服务器,因此我们需要将应用连接到它并使用某种“语言”进行交互,因此我们还需要一个连接工厂。

以下是spring-redis.xml配置

xmlns:cache=\ xmlns:context=\ xsi:schemaLocation=\

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/cache

http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd\>

p:hostName=\p:port=\p:poolConfig-ref=\ p:database=\/>

以下是redis.prperties配置文件的内容 redis.host=192.168.1.1 redis.port=6379 redis.pass= redis.maxIdle=300 redis.maxActive=600 redis.maxWait=1000 redis.maxTotal=30 redis.testOnBorrow=true

以下是RedisCache.java文件的内容

package com.yusys.common.cache.redis; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.springframework.cache.Cache;

import org.springframework.cache.support.SimpleValueWrapper; import org.springframework.dao.DataAccessException;

import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate;

publicclassRedisCacheimplements Cache {

private RedisTemplateredisTemplate; RedisCache(RedisTemplate redisTemplate){

this.redisTemplate=redisTemplate;

}

private String name;

publicvoid setName(String name) { this.name = name; } @Override

public String getName() { returnthis.name; } @Override

public Object getNativeCache() { returnthis.redisTemplate; } @Override

public ValueWrapper get(Object key) { final String keyf = (String) key; Object object = null;

object = redisTemplate.execute(new RedisCallback() {

public Object doInRedis(RedisConnection connection) throws DataAccessException {

byte[] key = keyf.getBytes(); byte[] value = connection.get(key); if (value == null) { returnnull; }

return toObject(value);

} });

return (object != null ? new SimpleValueWrapper(object) : null); } @Override

publicvoid put(Object key, Object value) { final String keyf = (String) key; final Object valuef = value; finallong liveTime = 86400; get(keyf);

redisTemplate.execute(new RedisCallback() {

public Long doInRedis(RedisConnection connection) throws DataAccessException { byte[] keyb = keyf.getBytes(); byte[] valueb = toByteArray(valuef);

connection.set(keyb, valueb); if (liveTime > 0) {

connection.expire(keyb, liveTime); } return 1L; } }); } /**

* 描述 : .
* <使用方法说明> */

privatebyte[] toByteArray(Object obj) { byte[] bytes = null;

ByteArrayOutputStream bos = new ByteArrayOutputStream(); try {

ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush();

bytes = bos.toByteArray(); oos.close(); bos.close();

} catch (IOException ex) { ex.printStackTrace(); } return bytes; }

private Object toObject(byte[] bytes) { Object obj = null; try {

ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); obj = ois.readObject(); ois.close(); bis.close();

} catch (IOException ex) { ex.printStackTrace();

} catch (ClassNotFoundException ex) { ex.printStackTrace(); } return obj; } @Override

publicvoid evict(Object key) { final String keyf = (String) key;

redisTemplate.execute(new RedisCallback() {

public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.del(keyf.getBytes()); } }); } @Override

publicvoid clear() {

redisTemplate.execute(new RedisCallback() {

public String doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return\; } }); }

@SuppressWarnings(\)

public T get(Object key, Class type) { final String keyf = (String) key; Object object = null;

object = redisTemplate.execute(new RedisCallback() {

public Object doInRedis(RedisConnection connection) throws DataAccessException { byte[] key = keyf.getBytes(); byte[] value = connection.get(key); if (value == null) { returnnull; }

return toObject(value); } });

return (T) object; }

public ValueWrapper putIfAbsent(Object key, Object value) { put(key, value);

returnnew SimpleValueWrapper(value); } }

3. spring注解调用redis

缓存注解有以下三个,在service里面对方法进行注解来使用:

@Cacheable(获取值) @CacheEvict(清空值) @CachePut(设置值)

key =\是将传入参数的值作为缓存的key,value =\是缓存操作对象的的name 返回值\;是存入缓存里面的值(将返回值存入缓存) @CachePut(key =\,value =\)

public String addUserByCache(String userno){//根据参数userno设置缓存数据,将返回值存入缓存

}

@CacheEvict(key =\,value =\)

publicvoid clearCache(String userno){//使用usercache和参数userno清空缓存 }

@Cacheable(key =\,value =\,condition =\) Publicvoid findCache(String userno){

//调用这个方法的时候,从一个名叫userCache的缓存中查询,如果没有,则执行实际的方法,并将结果存入缓存;

}

return\;

4. 缓存注解使用介绍

本文来源:https://www.bwwdw.com/article/4588.html

Top