Redis

soyo 2014-09-16

高并并发架构:

nginx+tomcat集群+Redis+ActiveMQ

redis缓存案例如下:

test代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/applicationContext.xml"})
public class UserDaoRedisTest {
   
        @Autowired
        private UserServiceRedis userServiceRedis;
       
        @Test 
        public void testCrud() { 
            // -------------- Create --------------- 
           
           
            String uid = "u123456"; 
            String address1 = "上海"; 
            User_Redis user = new User_Redis(); 
            user.setAddress(address1); 
            user.setUid(uid); 
            userServiceRedis.save(user);
           
            System.out.println("执行save....");
     
            // ---------------Read --------------- 
            user = userServiceRedis.read(uid); 
               
            assertEquals(address1, user.getAddress());
            System.out.println("执行read...."+user.getAddress()+user.getUid());
     
            // --------------Update ------------ 
            String address2 = "北京"; 
            user.setAddress(address2); 
            userServiceRedis.save(user); 
     
            user = userServiceRedis.read(uid); 
     
            assertEquals(address2, user.getAddress()); 
     
            // --------------Delete ------------ 
            userServiceRedis.delete(uid); 
            System.out.println("执行delete....");
            user = userServiceRedis.read(uid); 
            assertNull(user); 
        } 
}

RedisDao:

@Repository
public class UserDaoImplRedis implements UserDaoRedis {

    @Autowired 
    private RedisTemplate<Serializable, Serializable> redisTemplate;
   
    @Override
    public void save(final User_Redis user) {
        redisTemplate.execute(new RedisCallback<Object>() { 
            @Override 
            public Object doInRedis(RedisConnection connection) 
                    throws DataAccessException { 
                connection.set( 
                        redisTemplate.getStringSerializer().serialize( 
                                "user.uid." + user.getUid()), 
                        redisTemplate.getStringSerializer().serialize( 
                                user.getAddress())); 

                return null;
            } 
        }); 
    }
   
    public void saveObject(final User_Redis user) {
        redisTemplate.execute(new RedisCallback<Object>() { 
            @Override 
            public Object doInRedis(RedisConnection connection) 
                    throws DataAccessException { 
                connection.set( 
                        redisTemplate.getStringSerializer().serialize( 
                                "user.uid." + user.getUid()), 
                        redisTemplate.getStringSerializer().serialize( 
                                user.getAddress())
                                );
                connection.keys(redisTemplate.getStringSerializer().serialize("*"));
                return null;
            } 
        }); 
    }

    @Override
    public User_Redis read(final String uid) {
         return redisTemplate.execute(new RedisCallback<User_Redis>() { 
                @Override 
                public User_Redis doInRedis(RedisConnection connection) 
                        throws DataAccessException { 
                    byte[] key = redisTemplate.getStringSerializer().serialize( 
                            "user.uid." + uid); 
                    if (connection.exists(key)) { 
                        byte[] value = connection.get(key); 
                        String address = redisTemplate.getStringSerializer() 
                                .deserialize(value); 
                        User_Redis user = new User_Redis(); 
                        user.setAddress(address); 
                        user.setUid(uid); 
                        return user; 
                    } 
                    return null; 
                } 
            }); 
    }

    @Override
    public void delete(final String uid) {
        redisTemplate.execute(new RedisCallback<Object>() { 
            public Object doInRedis(RedisConnection connection) { 
                connection.del(redisTemplate.getStringSerializer().serialize( 
                        "user.uid." + uid)); 
                return null; 
            } 
        }); 
    }
}

Spring 配置:

 <!-- 自动扫描(自动注入) --> 
    <bean 
           id="jedisPoolConfig" 
           class="redis.clients.jedis.JedisPoolConfig" 
       > 
           <property 
               name="maxActive" 
               value="${redis.pool.maxActive}" /> 
           <property 
               name="maxIdle" 
               value="${redis.pool.maxIdle}" /> 
           <property 
               name="maxWait" 
               value="${redis.pool.maxWait}" /> 
           <property 
               name="testOnBorrow" 
               value="${redis.pool.testOnBorrow}" /> 
       </bean> 
      
         <bean 
        id="jedisConnectionFactory" 
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 
    > 
        <property 
            name="hostName" 
            value="${redis.ip}" /> 
        <property 
            name="port" 
            value="${redis.port}" /> 
        <property 
            name="poolConfig" 
            ref="jedisPoolConfig" /> 
    </bean> 
   
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" 
        p:connection-factory-ref="jedisConnectionFactory" />

引用的参数:

#最大分配的对象数 
redis.pool.maxActive=1024 
#最大能够保持idel状态的对象数 
redis.pool.maxIdle=200 
#当池内没有返回对象时,最大等待时间 
redis.pool.maxWait=1000 
#当调用borrow Object方法时,是否进行有效性检查 
redis.pool.testOnBorrow=true 
#IP 
redis.ip=127.0.0.1
#Port 
redis.port=6379 

pom.xml引用的包

<dependency>
              <groupId>org.springframework.data</groupId>
              <artifactId>spring-data-redis</artifactId>
              <version>1.0.2.RELEASE</version>
</dependency>

Redis服务端测试命令windows:
启动服务端:
cmd找到redis的跟目录下执行redis-server.exe redis.conf
测试客户端:
新开一个窗口cmd找到redis的跟目录下执行redis-cli.exe -h 127.0.0.1 -p 6379
127.0.0.1是我本机IP地址,端口6379就是上面配置文件中指定的监听端口
执行一条保存key value操作
set mystock 300156
再查询一下
get mystock

Redis session共享配置:

session 共享配置:
1、准备两个tomcat,端口区分开,例如8001,8002,注意一点是,tomcat server.xml其它端口也要修改为不同的,例如shutdown端口,否则无法同时启动两个tomcat
2、把同一个应用分别放置在两个tomcat中,然后测试是否正常访问两个应用。
3、停止tomcat,修改conf/文件夹下的context.xml文件,文件的context节点内添加如下配置,一定要注意h、p要和redis服务端配置的保持一致。
<Valve classname="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager classname="com.radiadesign.catalina.session.RedisSessionManager"
 host="127.0.0.1"
 port="6379"
 database="0"
 maxInactiveInterval="60" />
4、OK,配置完毕,来测试应用,启动tomcat1,直接登录应用,拷贝tomcat登陆后的URL,打开新的网页选项卡,粘贴tomcat1的地址,然后修改端口号为8002,然后访问
你会发现直接登录进去了。然后退出tomcat2的应用,刷新tomcat1的界面,你会发现tomcat1自动退出了,OK,证明session共享功能正确。

注意:配置session共享,在tomcat 的lib中要需要三个jar包,Commons-Pool   Jedis   tomcat-redis-session-manager
redis相关文章:http://blog.nosqlfan.com/html/3537.html

相关推荐