spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

网友投稿 326 2023-05-22


spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

maven项目中在pom.xml中依赖2个jar包,其他的spring的jar包省略:

redis.clients

jedis

2.8.1

org.springframework.data

spring-data-redis

1.7.2.RELEASE

spring-Redis.xml中的内容:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schemhttp://a/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:cache="http://springframework.org/schema/cache"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.2.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-4.2.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc-4.2.xshttp://d

http://springframework.org/schema/cache

http://springframework.org/schema/cache/spring-cache-4.2.xsd">

p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schemhttp://a/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xmlns:cache="http://springframework.org/schema/cache"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.2.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-4.2.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc-4.2.xshttp://d

http://springframework.org/schema/cache

http://springframework.org/schema/cache/spring-cache-4.2.xsd">

p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

redis-config.properties中的内容:

# Redis settings

# server IP

redis.host=127.0.0.1

# server port

redis.port=6379

# server pass

redis.pass=

# use dbIndex

redis.database=0

# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例

redis.maxIdle=300

# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;

redis.maxWait=3000

# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的

redis.testOnBorrow=true

com.cn.util.RedisCache类中的内容:

package com.cn.util;

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;

public class RedisCache implements Cache{

private RedisTemplate redisTemplate;

private String name;

public RedisTemplate getRedisTemplate() {

return redisTemplate;

}

public void setRedisTemplate(RedisTemplate redisTemplate) {

this.redisTemplate = redisTemplate;

}

public void setName(String name) {

this.name = name;

}

@Override

public String getName() {

// TODO Auto-generated method stub

return this.name;

}

@Override

public Object getNativeCache() {

// TODO Auto-generated method stub

return this.redisTemplate;

}

@Override

public ValueWrapper get(Object key) {

// TODO Auto-generated method stub

System.out.println("get key");

final String keyf = key.toString();

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) {

return null;

}

return toObject(value);

}

});

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

}

@Override

public void put(Object key, Object value) {

// TODO Auto-generated method stub

System.out.println("put key");

final String keyf = key.toString();

final Object valuef = value;

final long liveTime = 86400;

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;

}

});

}

private byte[] 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

public void evict(Object key) {

// TODO Auto-generated method stub

System.out.println("del key");

final String keyf = key.toString();

redisTemplate.execute(new RedisCallback() {

public Long doInRedis(RedisConnection connection)

throws DataAccessException {

return connection.del(keyf.getBytes());

}

});

}

@Override

public void clear() {

// TODO Auto-generated method stub

System.out.println("clear key");

redisTemplate.execute(new RedisCallback() {

public String doInRedis(RedisConnection connection)

throws DataAccessException {

connection.flushDb();

return "ok";

}

});

}

@Override

public T get(Object key, Class type) {

// TODO Auto-generated method stub

dXHkRZ return null;

}

@Override

public ValueWrapper putIfAbsent(Object key, Object value) {

// TODO Auto-generated method stub

return null;

}

}

到了这一步,大部分人会想在web.xml的启动配置文件地方(context-param)加入了spring-redis.xml,让项目启动时加载这个配置文件吧,但是这样启动后注解不生效。

正确的做法是:web.xml中配置了servlet控制器:

SpringMVC

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

/WEB-INF/spring-mvc.xml

1

true

在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为spring-mvc.xml的配置文件,如果不指定的话,默认是applicationContext.xml

只需要在spring-mvc.xml文件中引入spring-redis配置文件即可,正如spring-redis.xml中的启用注解说的:注解一定要声明在spring主配置文件中才会生效。

spring-mvc.xml内容,省略了spring与spring MVC整合的那部分:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.2.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-4.2.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc-4.2.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xmlns:mvc="http://springframework.org/schema/mvc"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.2.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-4.2.xsd

http://springframework.org/schema/mvc

http://springframework.org/schema/mvc/spring-mvc-4.2.xsd">

在service的实现类中:

@Service

public class UserServiceImpl implements UserService{

@Autowired

private UserBo userBo;

@Cacheable(value="common",key="'id_'+#id")

public User selectByPrimaryKey(Integer id) {

return userBo.selectByPrimaryKey(id);

}

@CachePut(value="common",key="#user.getUserName()")

public void insertSelective(User user) {

userBo.insertSelective(user);

}

@CacheEvict(value="common",key="'id_'+#id")

public void deleteByPrimaryKey(Integer id) {

userBo.deleteByPrimaryKey(id);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:React中ES5与ES6写法的区别总结
下一篇:配置Spring4.0注解Cache+Redis缓存的用法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~