SSM框架(二级缓存)集成Redis单机模式及哨兵模式

项目整体框架: SpringMVC + Spring+MyBatis +Redis(缓存部署在Linux虚拟机)。

数据库:mysql

1、整体架构

  • 参考Ehcache实现MyBatis二级缓存代码(Maven引用对应jar查阅)
  • 使用Spring管理Redis连接池
  • 模仿EhcacheCache,实现RedisCache
2、 pom.xml中加入Maven依赖
  • 
    	
    	
    	
    		
    		
    		    org.mybatis
    		    mybatis-ehcache
    		    1.0.0
    		
    		
    		
    		    org.springframework.data
    		    spring-data-redis
    		    1.8.6.RELEASE
    		
    		
    		    org.apache.commons
    		    commons-lang3
    		    3.4
    		
    		
    		    redis.clients
    		    jedis
    		    2.9.0
    		
    		
    		
    		
    		    org.springframework.session
    		    spring-session
    		    1.3.1.RELEASE
    		
    
    
    		
    		
    		
    			com.github.pagehelper
    			pagehelper
    			5.0.0
    		
    
    		
    		
    		
    			org.mybatis.generator
    			mybatis-generator-core
    			1.3.5
    		
    
    
    		
    			org.springframework
    			spring-webmvc
    			4.3.7.RELEASE
    		
    
    		
    		
    		
    			com.fasterxml.jackson.core
    			jackson-databind
    			2.8.8
    		
    		
    		
    		
    			org.hibernate
    			hibernate-validator
    			5.4.1.Final
    		
    		
    		
    		
    			org.springframework
    			spring-jdbc
    			4.3.7.RELEASE
    		
    		
    		
    		
    			org.springframework
    			spring-test
    			4.3.7.RELEASE
    		
    		
    		
    		
    			org.springframework
    			spring-aspects
    			4.3.7.RELEASE
    		
    		
    		
    		
    			org.mybatis
    			mybatis
    			3.4.2
    		
    		
    		
    		
    			org.mybatis
    			mybatis-spring
    			1.3.1
    		
    		
    		
    		
    			c3p0
    			c3p0
    			0.9.1
    		
    		
    		
    			mysql
    			mysql-connector-java
    			5.1.41
    		
    		
    		
    		
    			jstl
    			jstl
    			1.2
    		
    
    		
    		
    			javax.servlet
    			javax.servlet-api
    			3.0.1
    			provided
    		
    		
    		
    		
    		    log4j
    		    log4j
    		    1.2.17
    		
    		  
            
              org.slf4j  
              slf4j-log4j12  
              1.7.13  
            
    		
    		
    		
    			junit
    			junit
    			4.12
    		
    	
    3、Linux虚拟机Redis部署。
  • 3.1.下载解压redis(这里使用redis3.2.6的版本):
      
    cd /usr/software
    wget http://download.redis.io/releases/redis-3.2.6.tar.gz
    tar -zxvf /redis-3.2.6.tar.gz

3.2进行编译安装

	cd redis-3.2.6
	make && make install
3.3进行节点创建,这里为了目录结构清晰,创建一个文件夹进行集群文件的统一存放,并复制配置文件到相应的三个文件夹中

	cd /usr/software
	mkdir redis_cluster //创建集群目录
	cd redis_cluster
	mkdir 6379 7001 7002  //分别代表三个节点    其对应端口 6379 6380 6381
	cd ..
 	//创建7000节点为例,拷贝到7000目录
	 cp /usr/software/redis-3.2.6/redis.conf  ./redis_cluster/6379/
	 //拷贝到7001目录
	 cp /usr/software/redis-3.2.6/redis.conf  ./redis_cluster/6380/
 	//拷贝到7002目录
 	cp /usr/software/redis-3.2.6/redis.conf  ./redis_cluster/6381/

3.4.对应节点配置文件的修改以及sentinel.conf文件的创建配置

6379节点文件的修改:

redis.conf配置文件:

daemonize yes

pidfile "/var/run/redis6379.pid"

port 6379

bind 0.0.0.0

logfile "6379.log"

dbfilename "dump6379.rdb"

sentinel.conf的创建和配置:

port 26379

sentinel monitor mymaster192.168.108.128 6379

6380节点文件的修改:

redis.conf配置文件:

daemonize yes

pidfile "/var/run/redis6380.pid"

port6380

bind 0.0.0.0

logfile "6380.log"

dbfilename "dump6380.rdb"

slaveof 192.168.108.128 6380(映射到主服务器上)

sentinel.conf的创建和配置:

port 26380

sentinel monitor mymaster(主机名) 192.168.108.128 6380


6381节点文件的修改:

redis.conf配置文件:

daemonize yes

pidfile "/var/run/redis6381.pid"

port6381

bind 0.0.0.0

logfile "6381.log"

dbfilename "dump7002.rdb"

slaveof 192.168.108.128 6381(映射到主服务器上)

sentinel.conf的创建和配置:

port 26381

sentinel monitor mymaster192.168.108.128 6381

4.进行集群启动验证

分别在相应的文件夹进行启动:redis-server redis.conf 


并分别启动哨兵监控:redis-sentinel sentinel.conf 



以上是保证了linux下redis哨兵模式的部署成功,接下来是如何及集成到现有的SSM项目框架中

web.xml配置



  
  
    contextConfigLocation
    classpath:applicationContext.xml,classpath:spring-jedis-2.xml
  
  
  
    org.springframework.web.context.ContextLoaderListener
  

  
    dispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    1
  
  
    dispatcherServlet
    /
  
  
  
    CharacterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      utf-8
    
    
      forceRequestEncoding
      true
    
    
      forceResponseEncoding
      true
    
  
  
    CharacterEncodingFilter
    /*
  
  
    HiddenHttpMethodFilter
    org.springframework.web.filter.HiddenHttpMethodFilter
  
  
    HiddenHttpMethodFilter
    /*
  
  
  
    HttpPutFormContentFilter
    org.springframework.web.filter.HttpPutFormContentFilter
  
  
    HttpPutFormContentFilter
    /*
  
  
  
	
		springSessionRepositoryFilter
		org.springframework.web.filter.DelegatingFilterProxy
		
		
		springSessionRepositoryFilter
		/*
	
dispatcherServlet-servlet.xml配置信息:




	
	
		
		
	
	
	
	
		
		
	
	
	
	
	
	
	

applicationContext.xml配置信息:




	
		
	
	

	
	
	
	
		
		
		
		
	

	
	
		
		
		
		
		
	

	
	
		
		
	
	
	
	
		
		
	
	

	
	
		
		
	
	
	
	
	
		
			
			
			
			
		
	
	
	
		
		
		
		
	
	

	
	
	
mybatis-config.xml配置信息:




	
		
		 
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
	
	
	
		
	
	


以上是ssm整合的配置信息,下面是集成redis的整合

spring-jedis-2.xml(这里我做了两种的测试,为了配置文件区别,在后面进行了版本识别)


 
 	
	 
	    
	
    
 
	

 
  

        
        
        
        
        
        
        
    
 

	
	
		
		
			
				
			
		
		
		 
				
						
						
				
				
						
						
				
				
						
						
				
		  
		
	  
    
       
        
        
    
    
     
    
        
       
           
              
          
          
              
         
            
                
            
            
                
          
    
    
    
        
     
    
    
     
    
        
    
以下上java代码

RedisCache2.java

package com.atguigu.crud.cache;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;



public class RedisCache2 implements Cache {

    private static JedisConnectionFactory jedisConnectionFactory;
                                          
    private final String id;
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisCache2.class);
    
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    
    public RedisCache2(final String id){
        if (id == null) {
            throw new IllegalArgumentException("cache instances require an ID");
        }
        this.id = id;
    }
    
    
    @Override
    public void clear() {
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            connection.flushDb();
            connection.flushAll();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public Object getObject(Object key) {
    	LOGGER.info("hahahah");
        System.out.println("查询--------------------------------key:"+key);
        Object result = null;
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            result = serializer.deserialize(connection.get(serializer.serialize(key)));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (connection != null) {
                connection.close();
            }
        }
        
        return result;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    @Override
    public int getSize() {
        int result = 0;
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            result = Integer.valueOf(connection.dbSize().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    @Override
    public void putObject(Object key, Object value) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>key:"+key);
          
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            System.out.println("**"+serializer.serialize(key));
            connection.set(serializer.serialize(key), serializer.serialize(value));
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (connection != null) {
                connection.close();
            }
        }
        
    }

    @Override
    public Object removeObject(Object key) {
    	RedisConnection connection = null;
        Object result = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            result = connection.expireAt(serializer.serialize(key), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }


	public static JedisConnectionFactory getJedisConnectionFactory() {
		return jedisConnectionFactory;
	}


	public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
		RedisCache2.jedisConnectionFactory = jedisConnectionFactory;
	}
}RedisCacheTransfer.java 
  

package com.atguigu.crud.cache;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;


public class RedisCacheTransfer {
    
    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
       RedisCache2.setJedisConnectionFactory(jedisConnectionFactory);
    }
}

User.java

package com.atguigu.crud.bean;

import java.io.Serializable;

public class User implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String userName;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
}

UserDao.java(这里本人太懒 没有写太多方法)

package com.atguigu.crud.dao;

import com.atguigu.crud.bean.User;

public interface UserDao {
	public User queryByPK(Integer id);
}
UserMapper.xml




 
  


IUserService.java
package com.atguigu.crud.service;


import com.atguigu.crud.bean.User;


public interface IUserService {
	public User queryByPK(Integer id);
}
IUserServiceImpl.java

package com.atguigu.crud.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atguigu.crud.bean.User;
import com.atguigu.crud.dao.UserDao;
import com.atguigu.crud.service.IUserService;

@Service
public class IUserServiceImpl implements IUserService{
	@Autowired
	private UserDao userDao;
	@Override
	public User queryByPK(Integer id) {
		// TODO Auto-generated method stub
		return userDao.queryByPK(id);
	}
	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	

}

UserController.java

package com.atguigu.crud.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.crud.bean.User;
import com.atguigu.crud.service.IUserService;

@Controller
public class UserController {
	@Autowired
	private IUserService iUserService;
	@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
	@ResponseBody
	public User getHello(@PathVariable("id")Integer id,HttpServletRequest request){
		User user = iUserService.queryByPK(id);
		request.getSession().setAttribute("user", user);
		System.out.println(id);
		return user;
	}
	
	public IUserService getiUserService() {
		return iUserService;
	}

	public void setiUserService(IUserService iUserService) {
		this.iUserService = iUserService;
	}
	
}
测试效果:


SSM框架(二级缓存)集成Redis单机模式及哨兵模式_第1张图片


后台



测试故障转移(关闭主机)


SSM框架(二级缓存)集成Redis单机模式及哨兵模式_第2张图片



哨兵投票选取了6380端口为主机

SSM框架(二级缓存)集成Redis单机模式及哨兵模式_第3张图片


测试成功

以上是自己写的小测试 大家发现错误请告诉我下,谢谢

项目源码下载地址

http://download.csdn.net/download/wangxuelei036/9981864


你可能感兴趣的:(redis)