spring集成redis

spring集成redis总思路

 1. 导入对应的依赖
 2. 在spring的配制文件中启用缓存注解功能,编写redis.properties的配置信息
 3. 将redis的数据配(JedisPoolConfig)、连接池工厂(JedisConnectionFactory)、
 	redis模板(RedisTemplate)交给spring管理及在配制文件文件中创建对应的bean。
 4.编写缓存处理类,实现cache接口
 5.启用spring自己的管理器,用来管理自己创建的缓存类(RedisCache)。

目录结构

在这里插入图片描述

对应的jar坐标(注意版本问题)

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.6.RELEASE</version>
        </dependency>

对应的配置文件

<?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:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/cache
                       http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">、

 <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
    <cache:annotation-driven cache-manager="cacheManager" />
<!--配置redis开始-->

    <!--  redis数据源 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="#{redisConfig.maxIdle}"/>
        <property name="maxTotal" value="#{redisConfig.maxTotal}"/>
        <property name="testOnBorrow" value="#{redisConfig.testOnBorrow}"/>
        <property name="maxWaitMillis" value="#{redisConfig.maxWait}"/>
    </bean>

    <!--  Spring-redis连接池管理工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <!--ip地址-->
        <property name="hostName" value="#{redisConfig.host}"/>
        <!--端口号-->
        <property name="port" value="#{redisConfig.port}"/>
        <!--超时时间 默认2000-->
        <property name="timeout" value="#{redisConfig.timeout}"/>
        <!--连接池配置使用-->
        <property name="poolConfig" ref="poolConfig"/>
        <!--usePool:是否使用连接池-->
        <property name="usePool" value="true"/>
    </bean>


    <!--redis模板-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
        <!--开启事务-->
        <property name="enableTransactionSupport" value="true"/>
    </bean>

    <!--自定义redis工具类,在需要缓存的地方注入此类  -->
   <!-- <bean id="redisrCacheManager" class="com.dcy.utils.RedisCacheManager">
        <property name="redisTemplate" ref="redisTemplate"></property>
    </bean>-->

    <!--spring自己的缓存管理器,这里定义了缓存的位置,即注解中的value-->
    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <!-- 这里可以配置多个redis -->
                <!-- <bean class="com.cn.util.RedisCache">
                   <property name="redisTemplate" ref="redisTemplate" />
                   <property name="name" value="default"/>
                </bean> -->
                <bean class="com.dcy.utils.RedisCache">
                    <property name="redisTemplate" ref="redisTemplate"/>
                    <property name="name" value="common"/>
                    <!-- common名称要在类或方法的注解中使用 -->
                </bean>
            </set>
        </property>
    </bean>

    <!--redis结束-->

自己实现的缓存类

package com.dcy.utils;

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;

import java.io.*;
import java.util.concurrent.Callable;

public class RedisCache implements Cache{

    private RedisTemplate<String, Object> redisTemplate;
    private String name;
    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        // TODO Auto-generated method stub
        return this.name;
    }

    public Object getNativeCache() {
        // TODO Auto-generated method stub
        return this.redisTemplate;
    }

    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<Object>() {
            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);
    }

    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<Long>() {
            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;
    }

    public void evict(Object key) {
        // TODO Auto-generated method stub
        System.out.println("del key");
        final String keyf = key.toString();
        redisTemplate.execute(new RedisCallback<Long>() {
            public Long doInRedis(RedisConnection connection)
                    throws DataAccessException {
                return connection.del(keyf.getBytes());
            }
        });
    }

    public void clear() {
        // TODO Auto-generated method stub
        System.out.println("clear key");
        redisTemplate.execute(new RedisCallback<String>() {
            public String doInRedis(RedisConnection connection)
                    throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }

    public <T> T get(Object key, Class<T> type) {
        // TODO Auto-generated method stub
        return null;
    }

    public <T> T get(Object o, Callable<T> callable) {
        return null;
    }


    public ValueWrapper putIfAbsent(Object key, Object value) {
        // TODO Auto-generated method stub
        return null;
    }

}

对应的service


@Service
public class UserServiceImpl implements UserService{
 
	@Autowired
	private UserBo userBo;
 	/*
 		#id就是对应的参数
 	*/
	@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);
	}
}`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值