在ssm项目中使用redisTemplate

来源:互联网 发布:javascript简单游戏 编辑:程序博客网 时间:2024/05/20 02:54
  1. 第一步,导入相关的jar包:需要注意jedis和data-redis的版本,否则容易出现报错
<dependency>      <groupId>redis.clients</groupId>      <artifactId>jedis</artifactId>      <version>2.4.1</version>    </dependency>     <dependency>          <groupId>commons-pool</groupId>          <artifactId>commons-pool</artifactId>          <version>1.6</version>      </dependency>      <dependency>          <groupId>org.springframework.data</groupId>          <artifactId>spring-data-redis</artifactId>          <version>1.3.4.RELEASE</version>      </dependency>
  1. 在spring写相关的配置,由于笔者使用的spring版本略低,导致需要自己单独配置jedispoolConfig,首先就是 redisCopnfig.propertities文件
redis.host=localhostredis.port=6379redis.maxIdle=300redis.maxActive=600 redis.maxWait=1000redis.testOnBorrow=true
  1. 使用springMVC来统一载入配置文件
    spring-redis.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-4.2.xsd">    <context:property-placeholder location="classpath:redisConfig.properties" ignore-unresolvable="true" />    <bean id="MyjedisPoolConfig" class="com.xxx.MyjedisPoolConfig" >    </bean>     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"          p:host-name="${redis.host}" p:port="${redis.port}"  p:pool-config-ref="MyjedisPoolConfig"/>    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">        <property name="connectionFactory"   ref="connectionFactory" />    </bean> </beans>

4.其中所写的 com.xxx.MyjedisPoolConfig是重写了redis.clients.jedis.JedisPoolConfi中的JedisPoolConfig,

@Componentpublic class MyjedisPoolConfig extends  JedisPoolConfig{    @Value("${redis.maxIdle}")    private int maxIdle;    @Value("${redis.maxActive}")    private int maxTotal;    @Value("${redis.testOnBorrow}")    private boolean testOnBorrow;或者是使用以下写死的 /*   private int maxIdle=300;    private int maxTotal=600;    private boolean testOnBorrow=true;*/   public MyjedisPoolConfig(){}    public MyjedisPoolConfig(int maxIdle, int maxTotal,   boolean testOnBorrow) {        this.maxIdle = maxIdle;        this.maxTotal = maxTotal;        this.testOnBorrow = testOnBorrow;    }    @Override    public int getMaxIdle() {        return maxIdle;    }    @Override    public void setMaxIdle(int maxIdle) {        this.maxIdle = maxIdle;    }    @Override    public int getMaxTotal() {        return maxTotal;    }    @Override    public void setMaxTotal(int maxTotal) {        this.maxTotal = maxTotal;    }     @Override    public boolean getTestOnBorrow() {        return testOnBorrow;    }    public void setTestOnBorrow(boolean testOnBorrow) {        this.testOnBorrow = testOnBorrow;    }}
  1. 配置了spring的容器之后,就需要编写工具类了,spring-data-redis提供的redisTemplate类提供了对redis操作的简单封装,先写一个抽象类,然后写一个接口,然后实现之,
*抽象类,用于注入redisTemplate*public abstract class AbstractBaseRedisDao<K,V> {    public AbstractBaseRedisDao(){    }     @Autowired    protected RedisTemplate<K, V> redisTemplate;    /**     * 设置redisTemplate     * @param redisTemplate the redisTemplate to set     */    public void setRedisTemplate(RedisTemplate<K, V> redisTemplate){        this.redisTemplate=redisTemplate;    }    /**     * 获取 RedisSerializer     * <br>------------------------------<br>     */    protected RedisSerializer<String> getRedisSerializer() {        return redisTemplate.getStringSerializer();    }}*接口*public interface RedisSaveManageService {    /**     * 新增     * @return     */    boolean add(String key, String value);    /**     * 批量新增 使用pipeline方式     * @return     */    boolean add(List<String> key, List<String> values);    /**     * 删除     * @param key     */    void delete(String key);    /**     * 删除多个     * @param keys     */    void delete(List<String> keys);    /**     * 修改     * @return     */    boolean update(String key, String value);    /**     * 通过key获取     * @return     */    String get(String key); }*接口实现类:*@Servicepublic class RedisSaveManagerServiceImpl        extends AbstractBaseRedisDao<String, String> implements RedisSaveManageService {    /**     * 新增     * @return     */    @Override    public  boolean add( final String key,final String value) {        // TODO Auto-generated method stub        boolean result=redisTemplate.execute(new RedisCallback<Boolean>() {            @Override            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {                // TODO Auto-generated method stub                RedisSerializer<String> serializer=getRedisSerializer();                //序列化                byte[] key2=serializer.serialize(key);                byte[] value2=serializer.serialize(value);                return connection.setNX(key2, value2);            }        });        return result;    }    /**     * 批量新增 使用pipeline方式     *@return     */    @Override    public  boolean add(final List<String> key, final List<String> values) {        boolean result=redisTemplate.execute(new RedisCallback<Boolean>() {            @Override            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {                RedisSerializer<String> serializer=getRedisSerializer();                for (int i = 0; i < values.size(); i++) {                    byte[] key2=serializer.serialize(key.get(i));                    byte[] value2=serializer.serialize(values.get(i));                    connection.setNX(key2, value2);                }                return true;            }        },false,true);        return result;    }    @Override    public  void delete(String key) {        List<String> list = new ArrayList<>();        list.add(key);        delete(list);    }    @Override    public  void delete(final List<String> keys) {        redisTemplate.execute(new RedisCallback<Boolean>() {            @Override            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {                // TODO Auto-generated method stub                RedisSerializer<String> serializer=getRedisSerializer();                //序列化                for(String k:keys){                    byte[] key = serializer.serialize(k);                    connection.del(key);                }                return true;            }        });    }    @Override    public  boolean update(final String key,final String value) {        // TODO Auto-generated method stub        if (get(key) == null) {            throw new NullPointerException("数据行不存在, key = " + key);        }        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {            public Boolean doInRedis(RedisConnection connection)                    throws DataAccessException {                RedisSerializer<String> serializer = getRedisSerializer();                byte[] key2  = serializer.serialize(key);                byte[] value2 = serializer.serialize(value);                connection.set(key2, value2);                return true;            }        });        return result;    }    @Override    public String get(final String key) {        String result = redisTemplate.execute(new RedisCallback<String>() {            public String doInRedis(RedisConnection connection)                    throws DataAccessException {                RedisSerializer<String> serializer = getRedisSerializer();                byte[] key2 = serializer.serialize(key);                byte[] value = connection.get(key2);                if (value == null) {                    return null;                }                String value2 = serializer.deserialize(value);                return value2;            }        });        return result;    }} 
  1. 简单的使用,在controller中涉及到查询的部分,都可以先在redis中进行一次判断,如果没有,那就进入DB进行查询,查询到了就存储在redis中,为下一次查询使用,从而提高效率