网站前台的页面以及广告相关表结构
运营商后台广告类型管理与广告管理
前台工程广告轮播图的展示
SpringDataRedis操作字符串、set、List、hash等类型缓存
SpringDataRedis实现广告数据的缓存

一、网站前台分析
1.1、网站前台有哪些页面
(1)网站首页 index.html
(2)商家(店铺)首页 shop.html
(3)商品详细页 item.html
(4)商品搜索页 search.html
(5)购物车列表页 cart.html
(6)购物选项选择页 getOrderInfo.html
(7)支付页 pay.html
(8)用户注册页 register.html
(9)用户登陆页 login.html
(10)用户中心页等 home-*.html

1.2、网站首页广告
(1)首页海报(轮播图)
(2)今日推荐
(3)猜你喜欢
(4)楼层广告
1.3、数据库表结构分析
tb_content_category 广告分类表

tb_content 广告表

二、运营商后台-广告类型及广告管理
2.1、需求分析
实现广告类型表与广告表的增删改查

2.2、准备工作
2.2.1、构建工程
构建工程
(1)pinyougou-content-interface 
  引入依赖pinyougou-pojo
  创建包com.pinyougou.content.service
(2)pinyougou-content-service (WAR) 
  引入依赖参见pinyougou-sellergoods-service 
  引入tomcat插件配置 ,指定tomcat的运行端口为9002
  为pinyougou-content-service 工程添加web.xml 
  创建包 com.pinyougou.content.service.impl 
  添加spring相关配置文件

applicationContext-service.xml

<dubbo:protocol name="dubbo" port="20882"></dubbo:protocol> <!-- 访问注册中心时候的端口即客户端端口 -->
<dubbo:application name="pinyougou-content-service"/>  
<dubbo:registry address="zookeeper://192.168.25.128:2181"/>  <!-- zookeeper服务端端口 -->
<dubbo:annotation package="com.pinyougou.content.service.impl" />  

注意:我们目前有两个服务工程,当两个工程同时启动时会发生端口冲突,因为连接dubbox注册中心的端口默认是20880。所以我们需要配置一下pinyougou-content-service工程的dubbox端口 

(3)pinyougou-manager-web工程引入依赖pinyougou-content-interface
  因为使用@Refence实现了注入

2.2.2、生成代码拷贝入工程
使用代码生成器生成代码。代码生成器需要放在五中文和空格的文件夹下,不然会报错。

生成的文件:

拷贝interface、service、web、中的java代码。
拷贝JS中的service和controller的代码带manager-web的工程中。
测试运行广告分类管理和广告管理页面。

2.3、广告管理
2.3.1、广告图片上传
将pinyougou-shop-web的以下资源拷贝到pinyougou-manager-web
(1)UploadController.java 
(2)uploadService.js 
(3)application.properties
(4)fdfs_client.conf
在pinyougou-manager-web 的springmvc.xml中添加配置。–>配置多媒体解析器。

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:config/application.properties" />
    
    <!-- fastjson转换器配置 -->
    <mvc:annotation-driven>
      <mvc:message-converters register-defaults="true">
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">  
          <property name="supportedMediaTypes" value="application/json"/>
          <property name="features">
            <array>
              <value>WriteMapNullValue</value>
              <value>WriteDateUseDateFormat</value>
            </array>
          </property>
        </bean>
      </mvc:message-converters>  
    </mvc:annotation-driven>

    <!-- 配置多媒体解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 设定文件上传的最大值 5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>

    <!-- 引用dubbo 服务 -->
    <dubbo:application name="pinyougou-manager-web" />
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <dubbo:annotation package="com.pinyougou.manager.controller" />      

</beans>

View Code

在content.html中引入uploadService.js
修改content.html实现上传功能.  –>上传按钮绑定函数
在列表中显示图片。

2.3.2、广告类目选择
将contentCategoryService引入contentController
在content.html 引入contentCategoryService.js
在contentController.js中添加代码

//加载广告分类列表
$scope.findContentCategoryList=function(){
    contentCategoryService.findAll().success(
        function(response){
            $scope.contentCategoryList=response;                
        }
    );
}

View Code

在页面初始化调用该方法。
将广告类目改为下拉框。

2.3.3、广告状态  –即是否有效启用  1–使用  0–不使用
修改content.html 绑定变量,绑定true\false值。
在contentController.js 中定义变量数组  $scope.status=[“有效”,“无效”];
修改content.html  {{status[entity.status]}}

三、网站首页-广告展示
3.1、需求分析
修改首页,当其轮播广告图根据后台设置的广告列表动态产生。
3.2、准备工作
3.2.1、工程搭建
创建war模块pinyougou-portal-web ,此工程为网站前台的入口,参照其它war模块编写配置文件。不需要添加SpringSecurity框架

pom.xml中配置tomcat启动端口为9103

3.2、前端
(1)拷贝资源:资源文件夹中 “前台页面”目录下的index.html以及相关目录拷贝到

(2)添加angularJS库
(3)在js文件夹创建base.js 和 base_pagination.js  ,创建service 和controller文件夹

3.3、后端代码
3.3.1、服务接口层
在pinyougou-content-interface工程ContentService接口增加方法定义
3.3.2、服务实现层
在pinyougou-content-service工程ContentServiceImpl类增加方法
3.3.3、控制层
在pinyougou-portal-web创建控制器类 ContentController 
3.4、前端代码
3.4.1、服务层
在pinyougou-portal-web工程创建contentService.js
3.4.2、控制层
在pinyougou-portal-web创建contentController.js
3.4.3、页面
(1)修改pinyougou-portal-web工程的index.html 引入JS
在body上添加指令   先制造轮播图的地址

<body ng-app="pinyougou" ng-controller="contentController" ng-init="findByCategoryId(1)">

View Code

(2)修改首页轮播图

<!--banner轮播-->
<div id="myCarousel" data-ride="carousel" data-interval="4000" class="sui-carousel slide">
     <ol class="carousel-indicators">
         <li data-target="#myCarousel" data-slide-to="{{$index}}" class="{{$index==0?\'active\':\'\'}}" ng-repeat="item in contentList[1]" ></li>
     </ol>
     <div class="carousel-inner">
 <div class="{{$index==0?\'active\':\'\'}} item" ng-repeat="item in contentList[1]">
             <a href="{{item.url}}">
                    <img src="{{item.pic}}"  />
             </a>
      </div>
</div>
<a href="#myCarousel" data-slide="prev" class="carousel-control left"></a><a href="#myCarousel" data-slide="next" class="carousel-control right"></a>
</div>

View Code

四、SpringDataRedis简介
4.1、项目常见问题已思考
目前的系统已经实现了广告后台管理和广告前台展示,但是对于首页每天有大量的人访问,对数据库造成很大的访问压力,甚至是瘫痪。那如何解决呢?我们通常的做法有两种:一种是数据缓存、一种是网页静态化。我们今天讨论第一种解决方案。

4.2、Redis
redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写。企业开发通常采用Redis来实现缓存。同类的产品还有memcached 、MongoDB等。

4.3、Jedis
Jedis是Redis官方推出的一款面向Java的客户端,提供了很多接口供Java语言调用。可以在Redis官网下载,当然还有一些开源爱好者提供的客户端,如Jredis、SRP等等,推荐使用Jedis。

4.4、Spring Data Redis
Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis,  JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

spring-data-redis针对jedis提供了如下功能:
         1.连接池自动管理,提供了一个高度封装的“RedisTemplate”类
         2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
         ValueOperations:简单K-V操作
         SetOperations:set类型数据操作
         ZSetOperations:zset类型数据操作
         HashOperations:针对map类型的数据操作
         ListOperations:针对list类型的数据操作

4.5、Spring Data Redis入门demo
4.5.1、准备工作
(1)构建Maven工程  SpringDataRedisDemo
(2)引入Spring相关依赖、引入JUnit依赖   (内容参加其它工程)
(3)引入Jedis和SpringDataRedis依赖
  ===>需要添加的依赖包括junit  spring-core、spring-beans、spring-context spring-jdbc sprintg-test redis-clients spring-data-redis
spring-jms  spring-context-support
(4)在src/main/resources下创建properties文件夹,建立redis-config.properties

# Redis settings 
# server IP 
redis.host=127.0.0.1 
# server port 
redis.port=6379 
# server pass 
redis.pass= 
# use dbIndex 
redis.database=0 
redis.maxIdle=300 
redis.maxWait=3000 
redis.testOnBorrow=true

redis-config.properties

(5)在src/main/resources下创建spring文件夹 ,创建applicationContext-redis.xml

<?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:p="http://www.springframework.org/schema/p" 
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xmlns:cache="http://www.springframework.org/schema/cache"
  xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc.xsd 
            http://www.springframework.org/schema/cache  
            http://www.springframework.org/schema/cache/spring-cache.xsd">

  <context:property-placeholder location="classpath*:properties/*.properties" />
  <!-- redis 相关配置 -->
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="${redis.maxIdle}" />
    <property name="maxWaitMillis" value="${redis.maxWait}" />
    <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  </bean>
  <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="JedisConnectionFactory" />
  </bean>


</beans>  

applicationContext-redis.xml

  maxIdle:最大空闲数
  maxWaitMillis:连接时的最大等待毫秒数
  testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的;

4.5.2、值类型的操作
写在test 测试文件夹中
要点:
  @RunWidth(SpringJunit$ClassRunner.class)
  @ContextConfiguration(locations:”classpath: spring/applicationContext-redis.xml“)

redisTemplate.boundValueOps("name").set("itcast");    
String str = (String) redisTemplate.boundValueOps("name").get();
redisTemplate.delete("name");    

4.5.3、set类型操作

redisTemplate.boundSetOps("nameset").add("曹操");        
redisTemplate.boundSetOps("nameset").add("刘备");    
redisTemplate.boundSetOps("nameset").add("孙权");

Set members = redisTemplate.boundSetOps("nameset").members();
System.out.println(members);

redisTemplate.boundSetOps("nameset").remove("孙权");

redisTemplate.delete("nameset");

View Code

[刘备, 曹操, 孙权]
[]
remove方法是删除集合中的某个值。
delete方法是删除绑定的集合。

4.5.4、Lisrt类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestList {
    
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 右压栈:后添加的对象排在后边
     */

    @Test
    public void testSetValue(){
        redisTemplate.boundListOps("namelist1").rightPush("刘备");
        redisTemplate.boundListOps("namelist1").rightPush("关羽");
        redisTemplate.boundListOps("namelist1").rightPush("张飞");
    }

    /**
     * 显示右压栈集合
     */
    @Test
    public void testGetValue1(){
        List list = redisTemplate.boundListOps("namelist1").range(0, 10);
        System.out.println(list);
    }

    /**
     * 左压栈:后添加的对象排在前边
     */
    @Test
    public void testSetValue2(){
        redisTemplate.boundListOps("namelist2").leftPush("刘备");
        redisTemplate.boundListOps("namelist2").leftPush("关羽");
        redisTemplate.boundListOps("namelist2").leftPush("张飞");
    }

    /**
     * 显示左压栈集合
     */
    @Test
    public void testGetValue2(){
        List list = redisTemplate.boundListOps("namelist2").range(0, 10);
        System.out.println(list);
    }

    /**
     * 查询集合某个元素
     */
    @Test
    public void testSearchByIndex(){
        String s = (String) redisTemplate.boundListOps("namelist1").index(1);
        System.out.println(s);
    }

    /**
     * 移除集合某个元素
     */
    @Test
    public void testRemoveByIndex(){
        redisTemplate.boundListOps("namelist1").remove(1, "关羽");
    }


}

View Code

4.5.5、Hash类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext-redis.xml")
public class TestHash {
    
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSetValue(){
        redisTemplate.boundHashOps("namehash").put("a", "唐僧");
//        redisTemplate.boundHashOps("namehash").put("p", "payn");
        
        redisTemplate.boundHashOps("namehash").put("b", "悟空");
        redisTemplate.boundHashOps("namehash").put("c", "八戒");
        redisTemplate.boundHashOps("namehash").put("d", "沙僧");
    }


    //提取所有的key   是无序的
    @Test
    public void testGetKeys(){
        Set s = redisTemplate.boundHashOps("namehash").keys();
        System.out.println(s);
    }

    @Test
    public void testGetValues(){
        List values = redisTemplate.boundHashOps("namehash").values();
        System.out.println(values);
    }

    @Test
    public void testGetValueByKey(){
        Object object = redisTemplate.boundHashOps("namehash").get("b");
        System.out.println(object);
    }

    @Test
    public void testRemoveValueByKey(){
        redisTemplate.boundHashOps("namehash").delete("p");
    }


}

View Code

存入是无序的,相当于HashMap。重新添加,不会删除所有的内容在重新添加。也就是说后面的内容依然存在。

五、网站首页–缓存广告数据
5、网站首页-缓存广告数据 
5.1、需求分析
现在我们首页的广告每次都是从数据库读取,这样当网站访问量达到高峰时段,对数据库压力很大,并且影响执行效率。我们需要将这部分广告数据缓存起来。
5.2、读取缓存
5.2.1、公共组件层
因为缓存对于我们整个的系统来说是通用功能。广告需要用,其它数据可能也会用到,所以我们将配置放在公共组件层(pinyougou-common)中较为合理。
(1)pinyougou-common 引入依赖  –>主要是缓存相关的组件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.pinyougou</groupId>
        <artifactId>pinyougou-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>pinyougou-common</artifactId>

    <dependencies>
        <!-- 文件上传组件 -->
        <dependency>
            <groupId>org.csource.fastdfs</groupId>
            <artifactId>fastdfs</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

        <!-- 缓存 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>

    </dependencies>

</project>

View Code

(2)创建配置文件
将资源中的redis-config.propertiesapplicationContext-redis.xml 拷贝至pinyougou-common
(3)pinyougou-content-service依赖pinyougou-common
  这里需要重新install 以下common 工程。实际使用的配置文件时在maven仓库中的 jar 包中配置文件。

5.2.2、后端服务实现层
修改 pinyougou-content-service的ContentServiceImpl

@Autowired
private RedisTemplate redisTemplate;
    
@Override
public List<TbContent> findByCategoryId(Long categoryId) {
    
    List<TbContent> contentList = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);
    
    if(contentList==null) {
        //根据广告分类id找到广告列表
        TbContentExample example = new TbContentExample();
        Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);        //开启启用状态的
        example.setOrderByClause("sort_order");            //进行排序,使用数据库的字段
        contentList = contentMapper.selectByExample(example);
        redisTemplate.boundHashOps("content").put(categoryId, contentList);
        System.out.println("从数据库中进行查询");
    }else {
        System.out.println("从缓存中进行查询");
    }
    
    return contentList;
}

View Code

  首先是从redis缓存中找匹配的数据,没有的话就从数据库中找,并将找到的数据你放到redis缓存中。

5.3、更新缓存
当广告数据发生变更时,需要将缓存数据清除,这样再次查询才能获取最新的数据
5.3.1、新增广告后清除缓存
修改pinyougou-content-service工程ContentServiceImpl.java 的add方法

/**
 * 增加
 */
@Override
public void add(TbContent content) {
    contentMapper.insert(content);    
    //清除缓存
    redisTemplate.boundHashOps("content").rename(content.getCategoryId());
}

View Code

  –>新添加广告轮播图的时候,删除{“content”:[{“categoryId”:contentList},{}]}

5.3.2修改广告后清除缓存
考虑到用户可能会修改广告的分类,这样需要把原分类的缓存和新分类的缓存都清除掉。

/**
 * 修改
 */
@Override
public void update(TbContent content){
    //查询修改前的分类id-->因为这里还没有执行到dao层还没改变数据库中的数据
    Long categoryId0 = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
    //清除缓存
    redisTemplate.boundHashOps("content").delete(categoryId0);
    //执行更新的操作
    contentMapper.updateByPrimaryKey(content);
    //如果修改前后categoryId发生了改变
    if(categoryId0.longValue()!=content.getCategoryId().longValue()) {
        //清除缓存
        redisTemplate.boundHashOps("content").rename(content.getCategoryId());
    }
    
}

View Code

5.3.3删除广告后清除缓存

/**
 * 批量删除
 */
@Override
public void delete(Long[] ids) {
    for(Long id:ids){
        Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();
        //清除缓存
        redisTemplate.boundHashOps("content").delete(categoryId);
        contentMapper.deleteByPrimaryKey(id);
    }        
}

View Code

 

版权声明:本文为-zhuang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/-zhuang/articles/10416797.html