springboot 详解 (四)redis & filter

 ----------------------------------------------------------------------------------------------------------------

springboot 详解 (一) helloworld                                    下载demo          

springboot 详解 (二) crud                                             下载demo     

springboot 详解 (三) 多数据源                                        下载demo      

springboot 详解 (四)redis & filter                                    下载demo    

springboot 详解 (五)interceptor                                       下载demo     

springboot 详解 (六)servlet & scheduled & listener         下载demo     

springboot 详解(七) dubbox & zookeeper   下载(productor) 下载(constumser)

springboot 同步解耦 异步化 下载demo

springboot jenkins docker 部署 

springboot 详解(八) springboot & springcloud 

----------------------------------------------------------------------------------------------------------------

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;   
    } 

}


springboot 详解 (四)redis   & filter
 

package com.curiousby.cn.util;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

/**
 * 
 * @author vic
 * @desc json util 
 */
public class JSONUtil {
	
	private static Gson gson = null; 
	
	static{
		gson  = new Gson();//todo yyyy-MM-dd HH:mm:ss 
	}
	
	public static synchronized Gson newInstance(){
		if(gson == null){
			gson =  new Gson();
		}
		return gson;
	}
	
	public static String toJson(Object obj){
		return gson.toJson(obj);
	}
	
	public static <T> T toBean(String json,Class<T> clz){
		
		return gson.fromJson(json, clz);
	}
	
	public static <T> Map<String, T> toMap(String json,Class<T> clz){
		 Map<String, JsonObject> map = gson.fromJson(json, new TypeToken<Map<String,JsonObject>>(){}.getType());
		 Map<String, T> result = new HashMap<>();
		 for(String key:map.keySet()){
			 result.put(key,gson.fromJson(map.get(key),clz) );
		 }
		 return result;
	}
	
	public static Map<String, Object> toMap(String json){
		 Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String,Object>>(){}.getType());
		 return map;
	}
	
	public static <T> List<T> toList(String json,Class<T> clz){
		JsonArray array = new JsonParser().parse(json).getAsJsonArray();  
		List<T> list  = new ArrayList<>();
		for(final JsonElement elem : array){  
	         list.add(gson.fromJson(elem, clz));
	    }
	    return list;
	}
	
	public static void main(String[] args) {
	}
	
}
<dependency>  
          <groupId>org.springframework.boot</groupId>  
          <artifactId>spring-boot-starter-redis</artifactId>  
      </dependency> 
       
        
          <dependency>  
            <groupId>com.google.code.gson</groupId>  
            <artifactId>gson</artifactId>  
        </dependency>

相关推荐