论坛首页 入门技术论坛

springboot 详解 (四)redis

浏览 1678 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2016-11-17  

 

package com.curiousby.cn.redis;

import java.util.List;

 
public interface IRedisService {
	
	public boolean set(String key, String value);
	
	public boolean set(String key, String value,long expire);
	
	public String get(String key);
	
	public boolean expire(String key,long expire);
	
	public <T> boolean setList(String key ,List<T> list);
	
	public <T> List<T> getList(String key,Class<T> clz);
	
	public long lpush(String key,Object obj);
	
	public long rpush(String key,Object obj);
	
	public String lpop(String key);
	
}

 

package com.curiousby.cn.redis;

import org.apache.log4j.Logger;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import redis.clients.jedis.JedisPoolConfig;

/**
 * 
 * @author vic
 * @desc redis config bean
 *
 */
@Configuration
@EnableAutoConfiguration
public class RedisConfig {

	private static Logger logger = Logger.getLogger(RedisConfig.class);
	
	@Bean
	@ConfigurationProperties(prefix="spring.redis")
	public JedisPoolConfig getRedisConfig(){
		JedisPoolConfig config = new JedisPoolConfig();
		return config;
	}
	
	@Bean
	@ConfigurationProperties(prefix="spring.redis")
	public JedisConnectionFactory getConnectionFactory(){
		JedisConnectionFactory factory = new JedisConnectionFactory();
		JedisPoolConfig config = getRedisConfig();
		factory.setPoolConfig(config);
		logger.info("JedisConnectionFactory bean init success.");
		return factory;
	}
	
	
	@Bean
	public RedisTemplate<?, ?> getRedisTemplate(){
		RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory());
		return template;
	}
}

 

 

package com.curiousby.cn.redis;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import com.curiousby.cn.util.JSONUtil;

/**
 * 
 * @author 
 * @desc resdis service
 *
 */
@Service(value="redisService")
public class RedisServiceImpl implements IRedisService{

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Override
	public boolean set(final String key, final String value) {
		boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            	RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
	    });
		return result;
	}

	   @Override
	    public boolean set(final String key, final String value,final long expire) {
	        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
	            @Override
	            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
	                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
	                connection.set(serializer.serialize(key), serializer.serialize(value));
	                redisTemplate.expire(key, expire, TimeUnit.SECONDS);
	                return true;
	            }
	        });
	        return result;
	    }
	   
	public String get(final String key){
		String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
            	RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value =  connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
	    });
		return result;
	}

	@Override
	public boolean expire(final String key, long expire) {
		return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
	}

	@Override
	public <T> boolean setList(String key, List<T> list) {
		String value = JSONUtil.toJson(list);
		return set(key,value);
	}

	@Override
	public <T> List<T> getList(String key,Class<T> clz) {
		String json = get(key);
		if(json!=null){
			List<T> list = JSONUtil.toList(json, clz);
			return list;
		}
		return null;
	}

	@Override
	public long lpush(final String key, Object obj) {
		final String value = JSONUtil.toJson(obj);
		long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
            	RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
	    });
		return result;
	}

	@Override
	public long rpush(final String key, Object obj) {
		final String value = JSONUtil.toJson(obj);
		long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
            	RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
	    });
		return result;
	}

	@Override
	public String lpop(final String key) {
		String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
            	RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] res =  connection.lPop(serializer.serialize(key));
                return serializer.deserialize(res);
            }
	    });
		return result;
	}

}

 

spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0

 

package com.curiousby.cn.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.curiousby.cn.redis.IRedisService;

@WebFilter(filterName="ipFilter",urlPatterns="/*")
public class IPFilter  implements Filter {

    protected static final Logger logger = LoggerFactory.getLogger(IPFilter.class);
  
    
    public final static int IPMAXCOUNTPERMINUTES = 5;
    public final static long IPLIMITSENCONDS = 300;
    public final static long IPCOUNTSENCONDS = 60;
    
    
   // @Resource
    IRedisService iredisService;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
      
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request; 
        WebApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
        iredisService =  (IRedisService) wac.getBean("redisService");
        
        String ip = getIpAddr(req); 

        String ipLimit = iredisService.get(ip+"_limit");
        if (ipLimit !=null &&  !"".equals(ipLimit)) {
            req.getRequestDispatcher("/web/static/forward").forward(req, response);
            return;
        }else{
            String ipConut =  iredisService.get(ip+"_count");
            if (ipConut !=null &&  !"".equals(ipConut)){
                int ipLCount = Integer.parseInt(ipConut);
                if(ipLCount >= IPMAXCOUNTPERMINUTES){
                    iredisService.set(ip+"_limit", ipLCount+"", IPLIMITSENCONDS);
                    iredisService.set(ip+"_count", "0", IPCOUNTSENCONDS); 
                    req.getRequestDispatcher("/web/static/forward").forward(req, response);
                    return;
                }else{
                    ipLCount += 1; 
                    iredisService.set(ip+"_count", ipLCount+"", IPCOUNTSENCONDS); 
                } 
            }else{
                iredisService.set(ip+"_count", "1", IPCOUNTSENCONDS);
            }
        } 
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {
         
        
    }
    
    
    public String getIpAddr(HttpServletRequest request) {   
        String ip = request.getHeader("x-forwarded-for");   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("WL-Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getRemoteAddr();   
        }   
        return ip;   
    } 

}

 

 



 

 

 

 

 

 

 

 

 

 

 

  • 大小: 7.9 KB
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics