阅读354 返回首页    go 阿里云 go 技术社区[云栖]


Nginx + Shiro + Redis 实现负载均衡集群(成绩报告查询系统升级篇)

写在开始

上一篇讲到使用Ehcache实现分布式缓存,尽管其直接操作JVM内存,速度快,效率高,但是缓存同步麻烦,分布式集群配置不方便,如果应用服务器重启会丢失缓存数据。

下面来分析一下Redis做系统session缓存实现。

Redis介绍

Redis是一个key-value存储系统。和Memcached类似, 它的出现,很大程度补偿了memcached这类key/value存储的不足,在部 分场合可以对关系数据库起到很好的补充作用。它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。

Redis还支持主从同步。数据可以从主服务器向任意数量的从服务器上同步,从服务器可以关联其他从服务器的主服务器。

Redis是通过socket访问到缓存服务,效率比ecache低,但比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。

Redis安装

https://blog.52itstyle.com/archives/590/

项目架构

Spring MVC4 + Shiro-1.3.2 + Redis3.2.8

运行环境

Nginx + Tomcat7(3台) + JDK1.7

项目架构图

1

2

项目实现

Redis类库 jedis-2.9.0依赖commons-pool2-2.4.1

redis.properties配置:

#============================#
#===== redis sttings     ====#
#============================#
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
#单位秒
redis.expire=1800
redis.timeout=2000
redis.usepool=true
redis.database=1

重写 AbstractSessionDAO 和 CacheManager
applicationContext-redis.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:context="https://www.springframework.org/schema/context"
    xmlns:aop="https://www.springframework.org/schema/aop" xmlns:tx="https://www.springframework.org/schema/tx"
    xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <description>Shiro redisManager(集群环境下使用此配置,单点也可以使用)</description>
    <!-- shiro redisManager -->
    <bean  >
        <property name="host" value="${redis.host}" />
        <property name="password" value="${redis.password}"/>
        <property name="port" value="${redis.port}" />
        <property name="expire" value="${redis.expire}" />
        <property name="timeout" value="${redis.timeout}"/>
    </bean> 

    <!-- redisSessionDAO -->
    <bean  >
        <property name="redisManager" ref="redisManager" />
    </bean>
    <!-- cacheManager -->
    <bean  >
        <property name="redisManager" ref="redisManager" />
    </bean>

</beans>

声明:本文内容大体流程仅供参考,有些并未涉及到具体代码实现。

最后更新:2017-04-01 17:13:52

  上一篇:go (更新完结)阿里珍贵技术资料免费下载
  下一篇:go 【Java编码规范】《阿里巴巴Java开发手册(正式版)》更新(v1.1.1版)