将mysql中的全国区域表数据转移至Redis数据库

    搭建环境:

      1.meven工程

      2.Spring整合Mybatis框架

      3.Spring整合Redis数据库

 

    注:这里的大部分内容只有讲在java中如何使用Redis数据库

 

    一丶引入Redus相关jar包,包括Spring整合Redis的jar包

    关于jar包版本问题:

      目前我使用的这jar版本是没有出现问题的,但我换了一些版本后出现了报错,所以推荐使用我的jar版本即可

    

       <!--Redis驱动包-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.5.2</version>
        </dependency>
        <!--Spring整合Redis包-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.3.4.RELEASE</version>
        </dependency>
      <!---json格式化-->
    <dependency>    
      <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
  <version>1.1.41</version> </dependency>

  

  二丶首先创建两个properties文件分别保存两个数据的账号密码和相关配置和驱动

    jdbc.properties文件

    

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydatabase
jdbc.username=root
jdbc.password=admin

   

  redis.properties文件

redis.maxTotal=300
redis.maxWaitMillis=5000
redis.maxIdle=100
redis.testOnBorrow=true
redis.hostName=127.0.0.1
redis.password=
redis.port=6379

 

  三丶配置application项目运行环境,相应的配置文件如下,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       ">
    <!--ssm spring是领导  aop tx 是为了事务控制-->

    <!--@repository @Services-->
    <context:component-scan base-package="cn.bdqn.tangcco">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <context:property-placeholder location="classpath*:*.properties"/>
    <!--配置Redis连接池-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大连接数-->
        <property name="maxTotal" value="${redis.maxTotal}"></property>
        <!--最大空闲数-->
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <!--最大等待毫秒-->
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
        <!--设置是否验证连接的有效性-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
    </bean>
    <!--配置Redis连接池工厂-->
    <!--<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.hostName}"></property>
        <property name="password" value="${redis.password}"></property>
        <property name="port" value="${redis.port}"></property>
        <property name="usePool" value="true"></property>
        <property name="poolConfig" ref="jedisPoolConfig"></property>

    </bean>-->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <!--密码如果没有密码也需要写,即使写空的-->
        <property name="password" value="${redis.password}"></property>
        <!--连接地址-->
        <property name="hostName" value="${redis.hostName}"></property>
        <!--端口号-->
        <property name="port" value="${redis.port}"></property>
        <property name="usePool" value="true"></property>
        <!--连接池来源-->
        <property name="poolConfig" ref="jedisPoolConfig"></property>
    </bean>
    <!--配置Redis连接模板-->
    <bean class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
    </bean>
    <!--数据库连接池 copy-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--实体-->
        <property name="typeAliasesPackage" value="cn.entity"/>
        <!--mapper.xml-->
        <property name="mapperLocations" value="classpath:/mapper/*.xml"/>
    </bean>
    <!--Mybatis扫描接口位置-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--dao的接口-->
        <property name="basePackage" value="cn.*.dao"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="*" propagation="SUPPORTS"></tx:method>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* cn.*.services..*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
    </aop:config>

</beans>

 

    四丶编写区域表的实体类

  

public class Area {
    /**
     * 本区域表是自关联,
     */
//    地址编号
    private String areaid;
    //地址名称
    private String name;
    //地址类型
    private String type;
    //地址等级
    private String level;
    //改地址的父Id用于关联该地址在是属于哪个地区以及位置
    private String parentid;

    @Override
    public String toString() {
        return "Area{" +
                "areaid='" + areaid + '\'' +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", level='" + level + '\'' +
                ", parentid='" + parentid + '\'' +
                '}';
    }

    public String getAreaid() {
        return areaid;
    }

    public void setAreaid(String areaid) {
        this.areaid = areaid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getParentid() {
        return parentid;
    }

    public void setParentid(String parentid) {
        this.parentid = parentid;
    }
}

  五丶创建Dao利用Mybatis框架查询出地址表的数据,并分页查询,和查询地址表的总记录数

  DAO接口如下

  

  

public interface AreaDao {
    //查询list数据
    List<Area> queryAllArea(@Param("stast") Integer stast,@Param("pageSize") Integer pageSize);
    //查询总记录数让待会我们分页插入Redis数据库时更好的操作循环
    Integer queryCountArea();
}

  所对应的Mapper文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC
        "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.dao.AreaDao">
    <resultMap id="baseMap" type="cn.bdqn.tangcco.entity.Area" autoMapping="true">
        <id property="areaid" column="areaid"></id>
    </resultMap>
    <select id="queryAllArea" resultMap="baseMap">
      SELECT  * from area
      limit #{stast},#{pageSize}
    </select>
    <select id="queryCountArea" resultType="Integer">
        SELECT count(*) from area
    </select>
</mapper>

  六丶插入数据进入Redis数据和查询数据,一般来说我们页面所获取的数据都是json类型的,在我们插入时会把他转成json字符串,方便我们将数据传递至页面拿值

  注:

    在这里插入的数据类型是Redis的List数据类型,Key是mysql数据库中区域表的父Id作为Key

     

  services层接口代码方法

  

public interface RedisServices {
    void addAreas(List<Area> lists);
    List<String> queryAreaByParentId(String parent);
}

  Services 实现类

  

@Service
public class RedisServicesImpl implements RedisServices {
//    拿到Redis工厂模板
    @Inject
    private StringRedisTemplate redisTemplate;
    @Override
    public void addAreas(List<Area> lists) {
//        放进数据库的类型是list,拿到list类型对象
        ListOperations listOperations = redisTemplate.opsForList();
        if (lists!=null) {
            //循环增加的集合
            for (Area area:lists){
                //加入数据库,由于我们页面需要的是json串,直接把增加对象转化为json格式即可
                listOperations.leftPush("parentId"+area.getParentid(), JSONArray.toJSONString(area));
            }
        }
    }

    @Override
    public  List<String> queryAreaByParentId(String parent) {
        //获取Redis  List数据类型操作对象
        ListOperations listOperations = redisTemplate.opsForList();
        //根据传入的Key进行Redis数据库查询
        List<String> list = listOperations.range(parent,0,-1);
        return list;
    }
}

  七丶所有代码准备就绪,编写测试类

   测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestRedis  {
    @Inject
    RedisServices redisServices;
    @Inject
    private AreaDao areaDao;

 

  2.编写测试插入数据方法

    

 @Test
    public void testQueryAllAreaAndAddRedis(){
        //分页开始位置
        int stast = 0;
        //分页大小
        int pageSize = 1000;
        //总记录数
        int total = areaDao.queryCountArea();
        //求出总页数
        int totalPage=total%pageSize>0?1:0;
        totalPage += total/pageSize;
        /**
         * 思路:
         *      有多少页循环多少次
         *      务必把每一页的数据都加入Redis数据库
         */
        for (int i = 0;i<totalPage;i++){
            //从Mysql中查询出每一页的数据
            List<Area> list = areaDao.queryAllArea(stast,pageSize);
            //当前页数据都拿出来后,进行翻页,翻页就是把分页开始位置加上分页大小即可
            stast+=pageSize;
            //让控制台打印下每页数据,让我们跑程序时看见数据。并且有种期待感
            for (Area a :list){
                System.out.println(a);
            }
            //将从Mysql查询出来的数据加入Redis数据库
            redisServices.addAreas(list);
        }
    }

  3.加入完成后,可以用我们刚才编写的查看Redis数据库数据的方法进行查看

  

  @Test
    public void testAreaByParentId(){
        //想看哪一个层级的区域地址,直接传入参数即可
        for (String s:redisServices.queryAreaByParentId("parentId0")){
            System.out.println(s);
        }
    }

  到此完成

 

 

      

posted @ 2017-08-02 17:01  时光,  阅读(1768)  评论(0编辑  收藏  举报