向项目中添加redis缓存(整理)

1.添加redis配置文件redis.properties

redis.host=192.168.5.114

redis.port=6379

redis.maxIdle=100

redis.maxTotal=200

redis.maxWait=1000

redis.testOnBorrow=false

redis.timeout=10000

2.添加redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi  = "http://www.w3.org/2001/XMLSchema-instance"
    xmlns         = "http://www.springframework.org/schema/beans"
    xmlns:p       = "http://www.springframework.org/schema/p"
    xmlns:context = "http://www.springframework.org/schema/context"
    xmlns:mvc     = "http://www.springframework.org/schema/mvc"
    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/mvc     http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        <!-- redis -->
    
    
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        <property name="maxTotal" value="${redis.maxTotal}" /> 
        <property name="blockWhenExhausted" value="true" /> 
    </bean>
    
    <!-- jedis连接工程的配置 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="poolConfig" ref="jedisPoolConfig" /> 
        <!-- <property name="password" value="${redis.password}" /> -->
        <property name="usePool" value="true"/> 
        <property name="timeout" value="${redis.timeout}"></property>
    </bean> 

    <!-- redisTemplate配置 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">   
        <property name="connectionFactory"   ref="jedisConnectionFactory" />  
        <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> 
     </bean> 
    
</beans>

3.添加拦截器

<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/app/**/*.json*" />
            <bean class="com.censoft.app.main.ReadRedisHandlerInterceptor"/>  
        </mvc:interceptor> 
    </mvc:interceptors>

4.借助RedisTemplate进行增删改查

@Service
public class RedisMainDao {
    
    @Resource(name="redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 添加redis数据方法
     * @param key
     * @param value
     */
    public void addRedis(String key,String value){
         Object object = redisTemplate.opsForValue().get(key);
         if (object!=null) {
             redisTemplate.delete(key);
        }
            redisTemplate.opsForValue().set(key, value);
    }
    /**
     * 添加redis临时数据方法
     * @param key
     * @param value
     * @param timeMin
     */
    public void addRedisTime(String key,String value,long timeMin){
         Object object = redisTemplate.opsForValue().get(key);
         if (object!=null) {
             redisTemplate.delete(key);
        }
            redisTemplate.opsForValue().set(key, value,timeMin,TimeUnit.MINUTES);
        
    }
    /**
     * 获取redis数据方法
     * @param key
     */
    public String getRedis(String key){
        try {
            return (String) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
        
        
    }
    
    /**
     * 获取redis数据方法
     */
    public List<HashMap<String, String>> getRedisList(String keyPath){
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        Set<String> keys = redisTemplate.keys(keyPath+"*");
        
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            HashMap<String, String> map = new HashMap<String, String>();
            String key = it1.next();
            String value = getRedis(key);
            if(value.length()>100){
                value = value.substring(0, 100)+"...";
            }
            map.put("key", key);
            map.put("value", value.replaceAll(" ", ""));
            list.add(map);
        }
        return list;
    }
    
    /**
     * 获取redis数据方法
     */
    public List<HashMap<String, String>> getRedisList_main(){
        
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        List<String> lists = new ArrayList<String>();
        Set<String> keys = redisTemplate.keys("*");
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            HashMap<String, String> map = new HashMap<String, String>();
            String key = it1.next();
            int l = key.indexOf(":");
            if(l<0){
                l = key.length();
            }
            String keyPath = key.substring(0, l);
            int n = lists.indexOf(keyPath);
            if(n>-1){
                HashMap<String, String> map0 = list.get(n);
                map0.put("count", (Integer.valueOf(map0.get("count"))+1)+"");
            }else{
                lists.add(keyPath);
                map.put("key", keyPath);
                map.put("count", "1");
                list.add(map);
            }
        }
        
        
        Collections.sort(list,new Comparator<HashMap<String, String>>(){  
            public int compare(HashMap<String, String> arg0, HashMap<String, String> arg1) {  
                return arg0.get("key").compareTo(arg1.get("key"));  
            }
        }); 
        
        return list;
    }
    /**
     * 删除redis数据
     * @param key
     */
    public void removeRedis(String key){
        Set<String> keys = redisTemplate.keys(key+"*");
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            String keyd = it1.next();
            redisTemplate.delete(keyd);
        }
    }
    
    /**
     * 删除redis数据
     */
    public void removeRedisAllData(){
        Set<String> keys = redisTemplate.keys("*");
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            redisTemplate.delete(it1.next());
        }
    }
    
    public void removeRedisAllData(String index){
        Set<String> keys = redisTemplate.keys("*");
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            String key = it1.next();
            if(key.indexOf(index)>-1){
                redisTemplate.delete(key);
            }
        }
    }
    
    
    /**
     * 刷新redis数据
     */
    public List<String> reloadRedisByKey(String urlPath,String keyPath){
        List<String> list = new ArrayList<String>();
        Set<String> keys = redisTemplate.keys(keyPath+"*");
        Iterator<String> it1 = keys.iterator();
        while (it1.hasNext()) {
            String key = it1.next().replaceAll(":", "?");
            String url = urlPath + key;
            if(url.indexOf("?")>-1){
                url = url + "&clean=0";
            }else{
                url = url + "?clean=0";
            }
            list.add(url);
        }
        return list;
    }
    
    public long  getReidsTime(String key){
        long min=redisTemplate.getExpire(key,TimeUnit.MINUTES);
        return min;
    }
    
}

5.完善拦截器类 ReadRedisHandlerInterceptor

public class ReadRedisHandlerInterceptor extends HandlerMethodHandlerInterceptor {

//    CenConf cenConf = new CenConf();
    private static final ThreadLocal<HashMap> LOCAL = new ThreadLocal<HashMap>();
    
    @Autowired
    private RedisMainDao rs;
    
    @Autowired
    private CensearchService censearchService;
    
    @Override
    protected boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler)
            throws Exception {
//        HandlerMethod handlerMethod=(HandlerMethod) handler;
//        String controller = handlerMethod.getBean().getClass().getName();//控制器全限定名
//        String methodname = handlerMethod.getMethod().getName();//方法名
        
        String reqURL = request.getRequestURL().toString();
        
        HashMap<String, String> pramMap = parseRequest(request);
        String pram = pramMap.get("prams");
//        System.out.println(reqURL+"?"+pram);
        String b = pramMap.get("clean");
        
        if(reqURL.indexOf("/app/qyfwb/")>-1){
            return true;
        }
        if(reqURL.indexOf("/app/qyfwb/")>-1){
            return true;
        }
        
        if(reqURL.indexOf("app/main/getMdsInfo.json")>-1){
            if(reqURL.contains("getMdsInfo.jsonp")){
                b = "y";
            }else{
                return true;
            }
        }

        String key = reqURL.substring(reqURL.indexOf("lyjj")+4,reqURL.length());
        if(!"".equals(pram)){
            key = key + ":" + pram;
        }
        if(reqURL.indexOf("/app/censearch/search")>-1){
            censearchService.insertLog(key);
        }
//        System.out.println(key);
//        if(true){
//            rs.removeRedis(key);
//            return true;
//        }
        if("y".equals(b)){
            rs.removeRedis(key);
            String cleanValue = pramMap.get("cleanValue");
            if("nocache".equals(cleanValue)){
                return true;
            }
            if("all".equals(cleanValue)){
                rs.removeRedisAllData();
            }
            if("jsonp".equals(cleanValue)){
                rs.removeRedisAllData("jsonp");
            }
        }
        
//        System.out.println("key="+key);
        String jsonStr = rs.getRedis(key);
        if(jsonStr==null){
            HashMap<String, String> hm = new HashMap();
            hm.put("key", key);
            hm.put("isSave", "y");
            set(hm);
//            System.out.println("没有缓存数据:"+key);
            return true;
        }else{
//            System.out.println("直接返回:"+jsonStr);
            if(key.indexOf(".jsonp")>-1){
                jsonStr = "("+jsonStr+")";
                String functionName = pramMap.get("functionName");
                if(!"".equals(functionName) && functionName!=null){
                    jsonStr = functionName + jsonStr;
                }
            }
            JSONUtils.printString(jsonStr, response);
            return false;
        }
            
//        System.out.println(controller+"/"+methodname+"/"+responseStrBuilder.toString ());
        
    }
    
    @Override
    protected void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        super.postHandle(request, response, handler, modelAndView);
        HashMap<String, String> hm = get();
        if(hm!=null){
            String isSave = hm.get("isSave");
            if("y".equals(isSave)){
                String key = hm.get("key");
                if(modelAndView==null){
                    System.out.println(key+"-----modelAndView==null");
                    return;
                }else{
                    Map<String, Object> m = clMap(modelAndView.getModel());
                    String json = "";
                    try {
                        json = com.alibaba.druid.support.json.JSONUtils.toJSONString(m);
                        //json = json.replaceAll(":null", ":\"\"");
                        //存redis
                        rs.addRedis(key, json);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                
                
            }
        }
        
        
    }
    
    @Override
    protected void afterCompletion(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler,
            Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        
        set(null);
        
    }
    
    private static void set(HashMap hm){
        LOCAL.set(hm);
    }

    private static HashMap get(){
        return LOCAL.get();
    }
    
    private HashMap<String, String> parseRequest(HttpServletRequest request){
        HashMap<String, String> map = new HashMap<String, String>();
        String returnS = "";
        Map properties = request.getParameterMap();
        Iterator entries = properties.entrySet().iterator(); 
        Map.Entry entry; 
        String name = "";  
        String value = "";  
        String b = "n";
        String cleanValue = "";
        String functionName = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next(); 
            name = (String) entry.getKey(); 
            if("_".equals(name)){
                continue;
            }
            Object valueObj = entry.getValue(); 
            if(null == valueObj){ 
                value = ""; 
            }else if(valueObj instanceof String[]){ 
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){ 
                     value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            if("callback".equals(name)){
                map.put("functionName", value);
                continue;
            }
            if("clean".equals(name)){
                b = "y";
                cleanValue = value;
                continue;
            }
            returnS += "&"+name+"="+value;
        }
        
        //session  key为jd 时   拼上... 其他跳过
        Enumeration enumeration =request.getSession().getAttributeNames();
        while(enumeration.hasMoreElements()){
            String skey=enumeration.nextElement().toString();
            Object obj = request.getSession().getAttribute(skey);
            if(obj instanceof String){
                String svalue = obj.toString();
                if("jd".equals(skey)){
                    returnS += "&_"+skey+"="+svalue;
                }else if(returnS.indexOf(skey)>-1){
                    continue;
                }else{
                    continue;
                }
            }
        }
        
        if(returnS.length()>0){
            returnS = returnS.substring(1,returnS.length());
        }
                
        map.put("prams", returnS);
        map.put("clean", b);
        map.put("cleanValue", cleanValue);
        return map;
    }
    
    private Map<String, Object> clMap(Map<String, Object> map){
        for(Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object obj = entry.getValue();
            if("pagination".equals(key)){
                Pagination page = (Pagination)obj;
                HashMap hm = new HashMap();
                hm.put("pageNum", page.getPageNum());
                hm.put("pageSize", page.getPageSize());
                hm.put("totalCount", page.getTotalCount());
                hm.put("totalPages", page.getTotalPages());
                map.put("pagination", hm);
            }else if("org.springframework.validation.BindingResult.pagination".equals(key) || "mapList".equals(map)){
                map.remove(key);
            }else{
                if(obj==null){
                    map.put(key, "");
                }else{
                    if(obj instanceof List){
                        List<Object> list = (List<Object>) obj;
                        for(int i=0;i<list.size();i++){
                            Object o = list.get(i);
                            if(o instanceof Map){
                                Map<String,Object> map0 = (Map<String, Object>) o;
                                for(Entry<String, Object> entry0 : map0.entrySet()) {
                                    String key0 = entry0.getKey();
                                    Object value0 = entry0.getValue();
                                    if(value0==null){
                                        map0.put(key0, "");
                                    }
                                }
                            }else if(o instanceof String){
                                if(o==null){
                                    list.set(i, "");
                                }
                            }else{
                                System.out.println("未匹配类型.Object="+o);
                            }
                        }
                    }else if(obj instanceof Map){
                        Map<String,Object> map0 = (Map<String, Object>) obj;
                        for(Entry<String, Object> entry0 : map0.entrySet()) {
                            String key0 = entry0.getKey();
                            Object value0 = entry0.getValue();
                            if(value0==null){
                                map0.put(key0, "");
                            }
                        }
                    }else{
                        
                    }
                }
            }
        }
        return map;
    }
    
}

猜你喜欢

转载自www.cnblogs.com/winddogg/p/12652854.html