SSM(Spring 4.3.12.RELEASE + SpringMVC + Mybatis)整合 redis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37776094/article/details/79325172

前提:我已经在VMware中搭建好lmnt环境,可参考:http://blog.csdn.net/m0_37776094/article/details/79302797

同时启动redis服务,防火墙的6379端口也永久开放了

上述的博客只是对redis安装,具体开启远程配置还需要自己去百度。

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

已经安装好redis的同学可以跳过前面的废话.........

1、maven

        <!-- Redis客户端 -->  
    	<dependency>  
	        <groupId>redis.clients</groupId>   
	        <artifactId>jedis</artifactId>  
	        <version>2.7.2</version>  
    	</dependency>  
          
    	<!-- redis Spring  -->   
        <dependency>    
      		<groupId>org.springframework.data</groupId>    
      		<artifactId>spring-data-redis</artifactId>    
      		<version> 1.8.1.RELEASE</version>    
    	</dependency>  
2、添加配置文件spring-jedis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-4.2.xsd  
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd   
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd  
    http://www.springframework.org/schema/util   
    http://www.springframework.org/schema/util/spring-util-4.2.xsd">  
    
     <!-- 连接池配置 -->  
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
    	 <!-- 最大连接数 -->
        <property name="maxTotal" value="1000" />
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="500" />
        <!-- 每次释放连接的最大数目 -->
        <property name="numTestsPerEvictionRun" value="1024" />
        <!-- 释放连接的扫描间隔(毫秒) -->
        <property name="timeBetweenEvictionRunsMillis" value="30000" />
        <!-- 连接最小空闲时间 -->
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
        <property name="softMinEvictableIdleTimeMillis" value="10000" />
        <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
        <property name="maxWaitMillis" value="1500" />
        <!-- 在获取连接的时候检查有效性, 默认false -->
        <property name="testOnBorrow" value="true" />
        <!-- 在空闲时检查有效性, 默认false -->
        <property name="testWhileIdle" value="true" />
        <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
        <property name="blockWhenExhausted" value="false" />
    </bean>  
       
    <!-- jedis客户端单机版 -->  
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg name="host" value="192.168.40.100" /> 
        <constructor-arg name="port" value="6379" type="int" /> 
        <constructor-arg name="password" value="123456" /> 
        <constructor-arg name="timeout" value="3000" type="int"/>
        <constructor-arg name="database" value="0" type="int"/> <!--必须要,否则报错,没具体深入了解-->
        <constructor-arg name="poolConfig" ref="jedisPoolConfig"/> 
     </bean> 
 </beans>  
3、在spring配置文件(spring-application.xml)中引入spring-jedis.xml
    <!-- 引入redis配置文件 -->
    <import resource="classpath:conf/spring-jedis.xml"/>

4、开始编写redis工具辅助类-抽象Key(防止key一样,被覆盖)


public interface KeyPrefix {
    public int expireSeconds();
    public String getPrefix();   
 } 


public abstract class BasePrefix implements KeyPrefix{
    private int expireSeconds;
    
    private String prefix;
    
    public BasePrefix(String prefix) {//0代表永不过期
        this(0, prefix);
    }
    
    public BasePrefix( int expireSeconds, String prefix) {
        this.expireSeconds = expireSeconds;
        this.prefix = prefix;
    }
    
    public int expireSeconds() {//默认0代表永不过期
        return expireSeconds;
    }

    public String getPrefix() {
        String className = getClass().getSimpleName();
        return className+":" + prefix;
    }
}

public class UserKey extends BasePrefix{

    public static final int TOKEN_EXPIRE = 3600 * 24 * 1;
    public UserKey(int expireSeconds, String prefix) {
        super(expireSeconds, prefix);
    }

    public static UserKey token = new UserKey(TOKEN_EXPIRE, "tk");
    public static UserKey getById = new UserKey(0, "id");
    
}


5、jedis通用接口redisService.java

public interface RedisService {

	/**
	 * 获取当个对象
	 * */
	public <T> T get(KeyPrefix prefix, String key,  Class<T> clazz);
	
	/**
	 * 设置对象
	 * */
	public <T> boolean set(KeyPrefix prefix, String key,  T value);
	
	/**
	 * 判断key是否存在
	 * */
	public <T> boolean exists(KeyPrefix prefix, String key);
	
	/**
	 * 删除
	 * */
	public boolean delete(KeyPrefix prefix, String key);
	
	
	/**
	 * 增加值
	 * */
	public <T> Long incr(KeyPrefix prefix, String key);
	
	/**
	 * 减少值
	 * */
	public <T> Long decr(KeyPrefix prefix, String key);
	
	public boolean delete(KeyPrefix prefix);
	
	public List<String> scanKeys(String key);
	
	public <T> String beanToString(T value);
	
	public <T> T stringToBean(String str, Class<T> clazz);
	
}
6、实现类
@Service("redisService")
public class RedisServiceImpl implements RedisService{

    @Autowired
    private JedisPool  jedisPool; 


	/**
	 * 获取当个对象
	 * */
	@Override
	public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {
		Jedis jedis = null;
		 try {
			 jedis =  jedisPool.getResource();
			 //生成真正的key
			 String realKey  = prefix.getPrefix() + key;
			 String  str = jedis.get(realKey);
			 T t =  stringToBean(str, clazz);
			 return t;
		 }catch (Exception e) {
			 e.printStackTrace();
			 returnToPool(jedis);
			 return null;
		 }finally {
			 returnToPool(jedis);
		 }
	}

	/**
	 * 设置对象
	 * */
	@Override
	public <T> boolean set(KeyPrefix prefix, String key, T value) {
		Jedis jedis = null;
		 try {
			 jedis =  jedisPool.getResource();
			 String str = beanToString(value);
			 if(str == null || str.length() <= 0) {
				 return false;
			 }
			//生成真正的key
			 String realKey  = prefix.getPrefix() + key;
			 int seconds =  prefix.expireSeconds();
			 if(seconds <= 0) {
				 jedis.set(realKey, str);
			 }else {
				 jedis.setex(realKey, seconds, str);
			 }
			 return true;
		 }catch (Exception e) {
			 e.printStackTrace();
			 returnToPool(jedis);
			 return false;
		 }finally {
			 returnToPool(jedis);
		 }
	}

	/**
	 * 判断key是否存在
	 * */
	@Override
	public <T> boolean exists(KeyPrefix prefix, String key) {
		Jedis jedis = null;
		 try {
			 jedis =  jedisPool.getResource();
			//生成真正的key
			 String realKey  = prefix.getPrefix() + key;
			return  jedis.exists(realKey);
		 }finally {
			  returnToPool(jedis);
		 }
	}

	/**
	 * 删除
	 * */
	@Override
	public boolean delete(KeyPrefix prefix, String key) {
		Jedis jedis = null;
		 try {
			 jedis =  jedisPool.getResource();
			//生成真正的key
			String realKey  = prefix.getPrefix() + key;
			long ret =  jedis.del(realKey);
			return ret > 0;
		 }finally {
			  returnToPool(jedis);
		 }
	}

	/**
	 * 增加值
	 * */
	public <T> Long incr(KeyPrefix prefix, String key) {
		Jedis jedis = null;
		 try {
			 jedis =  jedisPool.getResource();
			//生成真正的key
			 String realKey  = prefix.getPrefix() + key;
			return  jedis.incr(realKey);
		 }finally {
			  returnToPool(jedis);
		 }
	}

	/**
	 * 减少值
	 * */
	public <T> Long decr(KeyPrefix prefix, String key) {
		 Jedis jedis = null;
		 try {
			 jedis =  jedisPool.getResource();
			//生成真正的key
			 String realKey  = prefix.getPrefix() + key;
			return  jedis.decr(realKey);
		 }finally {
			  returnToPool(jedis);
		 }
	}

	public boolean delete(KeyPrefix prefix) {
		if(prefix == null) {
			return false;
		}
		List<String> keys = scanKeys(prefix.getPrefix());
		if(keys==null || keys.size() <= 0) {
			return true;
		}
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.del(keys.toArray(new String[0]));
			return true;
		} catch (final Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if(jedis != null) {
				jedis.close();
			}
		}
	}

	public List<String> scanKeys(String key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			List<String> keys = new ArrayList<String>();
			String cursor = "0";
			ScanParams sp = new ScanParams();
			sp.match("*"+key+"*");
			
			sp.count(100);
			do{
				ScanResult<String> ret = jedis.scan(cursor, sp);
				List<String> result = ret.getResult();
				if(result!=null && result.size() > 0){
					keys.addAll(result);
				}
				//再处理cursor
				cursor = ret.getStringCursor();
			}while(!cursor.equals("0"));
			return keys;
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
	}
		
	public <T> String beanToString(T value) {
		if(value == null) {
			return null;
		}
		Class<?> clazz = value.getClass();
		if(clazz == int.class || clazz == Integer.class) {
			 return ""+value;
		}else if(clazz == String.class) {
			 return (String)value;
		}else if(clazz == long.class || clazz == Long.class) {
			return ""+value;
		}else {
			return JSON.toJSONString(value);
		}
	}
	
	@SuppressWarnings("unchecked")
	public <T> T stringToBean(String str, Class<T> clazz) {
    		if(str == null || str.length() <= 0 || clazz == null) {
			 return null;
		}
		if(clazz == int.class || clazz == Integer.class) {
			 return (T)Integer.valueOf(str);
		}else if(clazz == String.class) {
			 return (T)str;
		}else if(clazz == long.class || clazz == Long.class) {
			return  (T)Long.valueOf(str);
		}else {
			return JSON.toJavaObject(JSON.parseObject(str), clazz);
		}
	}

	private void returnToPool(Jedis jedis) {
		 if(jedis != null) {
			 jedis.close();
		 }
	}

	
}
7、测试类Controller(我这里写的是api,基于swagger2的)
@Autowired
RedisService redisService;
	
    @ApiOperation(value="get", notes="")
    @GetMapping(value = "/redis/get")
    public ResponseEntity<ResponseData>  redisGet(
    		@RequestParam(required = true) String appkey,
    		@RequestParam(required = true) String value) {
    	User  user  = redisService.get(UserKey.getById, ""+value, User.class);
    	message.returnData(user);
        return new ResponseEntity<ResponseData>(message, HttpStatus.OK);
    }
	
    @ApiOperation(value="set", notes="")
    @PostMapping(value = "/redis/set")
    public ResponseEntity<ResponseData>  redisSet(
    		@RequestParam(required = true) String appkey,
    		@RequestParam(required = true) String value) {
		User user  = new User();
    	user.setUserid(value);
    	user.setUsername(value);
    	redisService.set(UserKey.getById, ""+value, user);//UserKey:id1
    	message.returnData(user);
        return new ResponseEntity<ResponseData>(message, HttpStatus.OK);
    }
8、redis可视化管理工具(windows)





猜你喜欢

转载自blog.csdn.net/m0_37776094/article/details/79325172