Redis缓存技术在windows上的应用

3/8/2017来源:ASP.NET技巧人气:1660

1.首先准备好相应的jar包

2.修改apache-tomcat\conf\context.xml,在后面加上以下部分,以下部分可以在里面添加redis服务器密码,但是在tomcat配置文件中也要相对应

3.如何打算把项目做集群的话,需要修改tomcat的server.xml配置文件,保证集群里的tomcat服务器的端口都是唯一的

4.把准备好的Redis的jar包导入tomcat的lib文件夹里,把需要跑的项目打包成war包,放到tomcat的webapps目录下,需要保证各个tomcat的war包是相同的。 5.配置Nginx:打开conf\nginx.conf文件。我以两台tomcat服务器为例,需要在该文件添加以下代码

即配置对应的端口和需要跑的项目。 6.接下来配置项目里的sPRing-config.xml:在里面加入扫包的路径<context:component-scan base-package="com.xxl.common.redis" />,在对应的路径加入以下代码。

package com.xxl.common.redis;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;

/**
 * 定义配置类注入容器(@Configuration等价于xml的beans) 启用缓存支持,定义一个RedisCacheManager管理bean
 * 
 * @author Administrator
 *
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    private static final String host = "127.0.0.1";
    private static final int port = 6379;
    //private static final String pwd = "abcd6666";

    @Bean(name = "redisConnectionFactory")
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
        redisConnectionFactory.setHostName(host);
        redisConnectionFactory.setPort(port);
        //redisConnectionFactory.setPassWord(pwd);
        return redisConnectionFactory;
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(cf);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(7200);
        return cacheManager;
    }

    /**
     * 自定义缓存策略(保证key值的唯一性)
     * 
     * @return
     */
    @Bean
    public KeyGenerator customKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
}
package com.xxl.common.redis;

import org.springframework.context.applicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;


public class RedisService {
    
    public static ApplicationContext ctx;
    
    public static RedisConnectionFactory redisConnectionFactory;
    
    public static RedisTemplate<String, String> redis;
    
    public static void main(String[] args) {
        ctx = new ClassPathXmlApplicationContext("spring-config.xml");
        redis = ctx.getBean("redisTemplate", RedisTemplate.class);
        redis.opsForHash().put("b", "1", "fff");
        String key = (String) redis.opsForHash().get("b","1");
        System.err.println(key);
        //redis.delete(key);
        //System.out.println(redis);
        //redis.opsForValue().set("xman", "abc");
        //System.err.println(redis.opsForValue().get("xman"));
    }
    
}
然后把两个tomcat跑起来,再启动nginx和Redis服务器,进入redis客户端:redis-cli.exe。


如果想做到登录的唯一性可以在登录里加入以下代码

/**      * 缓存session到redis      */     void redisSession(UserInfo userInfoDB, String sessionId) {         // 将sessionid缓存到redis,防止一个账户多次登陆         if (null != redisTemplate.opsForValue().get(userInfoDB.getId() + "XxlUid")) {             String redisValue = (String) redisTemplate.opsForValue().get(userInfoDB.getId() + "XxlUid");             // 删除之前用户sessionid             redisTemplate.delete(redisValue);         }         redisTemplate.opsForValue().set(userInfoDB.getId() + "XxlUid", sessionId);     }

如果为了减轻数据库端的负担,优化性能可以在业务层加入以下注解:

package com.xxl.common.bo;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.xxl.common.dao.IRedisTestDao;
import com.xxl.common.entity.RedisTest;

@Service("redisTestBo")
public class RedisTestBo implements IRedisTestBo {
    
    private final Log logger = LogFactory.getLog(this.getClass());
    
    @Resource  
    private IRedisTestDao redisTestDao;
//下面注解表示除了第一次直接查询数据库以外,以后都是从redis数据库里面读取数据而不是MySQL数据库,allEntries=true的
//意思是对数据进行了增删改后更新到mysql数据库
    @CacheEvict(value = { "selectByCode"}, allEntries = true)
    public int deleteByCode(String code) {
        logger.debug("every body 一起嗨 // delete");
        redisTestDao.deleteByCode(code);
        return 1;
    }

    @CacheEvict(value = { "selectByCode"}, allEntries = true)
    public int insert(RedisTest redisTest) {
        logger.debug("every body 一起嗨 // add");
        return redisTestDao.insert(redisTest);
    }
    
    @Cacheable("selectByCode")
    public List<RedisTest> selectByCode(String code) {
        logger.debug("every body 一起嗨 // read");
        return redisTestDao.selectByCode(code);
    }
    
    @CacheEvict(value = { "selectByCode"}, allEntries = true)
    public int updateById(RedisTest redisTest) {
        logger.debug("every body 一起嗨 // update");
        return redisTestDao.updateById(redisTest);
    }
    
}