概述

本篇将介绍如下几个方面:

完成运营商后台广告类型管理与广告管理、完成前台工程广告轮播图的展示、使用SpringDataRedis操作字符串、set、List、hash等类型缓存、使用SpringDataRedis实现广告数据的缓存。

广告管理

1.后台管理

1.1搭建广告工程

基于高内聚低耦合的原则,我们需要单独搭建广告服务工程。

具体操作和创建pinyougou-sellergoods服务工程差不多,这里给出几点注意事项:

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

2、由于需要用到上传服务,还需要添加common工具包的依赖

1.2广告图片上传

将pinyougou-shop-web有关服务上传的资源拷贝到pinyougou-manager-web

在pinyougou-manager-web 的springmvc.xml中添加配置

<!-- 配置多媒体解析器 -->
<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>

在contentController.js编写代码(注意引入uploadService)

//上传广告图
$scope.uploadFile=function(){uploadService.uploadFile().success(function(response){if(response.success){$scope.entity.pic=response.message;                   }else{alert("上传失败!");}}).error(function(){alert("上传出错!");});
}

修改content.html实现上传功能

<tr>            <td>图片</td><td><input type="file" id="file"><button ng-click="uploadFile()">上传</button>                                <img alt="" src="{{entity.pic}}" height="100px" width="200px"></td>
</tr>

1.3广告类目选择

在contentController.js中添加代码

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

在content.html 初始化调用此方法,将广告分类改为下拉列表

<select  class="form-control" ng-model="entity.categoryId" ng-options="item.id as item.name  for item in contentCategoryList"></select>

1.4广告状态

修改content.html

<input  type="checkbox" ng-model="entity.status" ng-true-value="1" ng-false-value="0">

修改contentController.js

$scope.status=["无效","有效"];

2.前台展示

修改首页,当其轮播广告图根据后台设置的广告列表动态产生。

2.1搭建门面工程

创建war模块pinyougou-portal-web ,此工程为网站前台的入口,参照其它war模块编写配置文件。不需要添加SpringSecurity框架

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

2.2后端实现

在pinyougou-content-interface工程ContentService接口增加方法定义

/*** 根据广告类型ID查询列表* @param key* @return*/
public List<TbContent> findByCategoryId(Long categoryId);

在pinyougou-content-service工程ContentServiceImpl类增加方法

@Override
public List<TbContent> findByCategoryId(Long categoryId) {TbContentExample example = new TbContentExample();Criteria criteria = example.createCriteria();criteria.andCategoryIdEqualTo(categoryId);criteria.andStatusEqualTo("1");//条件:有效example.setOrderByClause("sort_order");//排序return contentMapper.selectByExample(example);
}

在pinyougou-portal-web创建控制器类 ContentController

@RestController
@RequestMapping("/content")
public class ContentController {@Referenceprivate ContentService contentService;/*** 根据广告分类ID查询广告列表* @param categoryId* @return*/@RequestMapping("/findByCategoryId")public List<TbContent> findByCategoryId(Long categoryId) {return contentService.findByCategoryId(categoryId);}}

2.3前端代码

在pinyougou-portal-web工程创建contentService.js

app.service("contentService",function($http){//根据分类ID查询广告列表this.findByCategoryId=function(categoryId){return $http.get("content/findByCategoryId.do?categoryId="+categoryId);}
});

在pinyougou-portal-web创建contentController.js

//广告控制层(运营商后台)
app.controller("contentController",function($scope,contentService){   $scope.contentList=[];//广告集合   $scope.findByCategoryId=function(categoryId){contentService.findByCategoryId(categoryId).success(function(response){$scope.contentList[categoryId]=response;});       }
});

在body上添加指令

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

修改首页轮播图

<div class="yui3-u Center banerArea"><!--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>

这里首个循环需要增加class=“active”,效果是直接显示,否则可能页面会先出现一段空白,极不美观。

效果:

缓存解决方案

首页每天有大量的人访问,对数据库造成很大的访问压力,甚至是瘫痪。我们通常的做法有两种:一种是数据缓存、一种是网页静态化。我们今天讨论第一种解决方案。

1.SpringDataRedis简介

1.1演变过程

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

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

3、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类型的数据操作

1.2配置

pom.xml需要引入Jedis和SpringDataRedis依赖

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

resources下创建properties文件夹,建立redis-config.properties

redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true

maxIdle :最大空闲数

maxWaitMillis:连接时的最大等待毫秒数

testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的;

resources下创建spring文件夹 ,创建applicationContext-redis.xml

<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>

1.3Value类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestValue {@Autowiredprivate RedisTemplate redisTemplate; @Testpublic void setValue(){redisTemplate.boundValueOps("name").set("itcast");     }   @Testpublic void getValue(){String str = (String) redisTemplate.boundValueOps("name").get();System.out.println(str);}   @Testpublic void deleteValue(){redisTemplate.delete("name");;}
}

1.4Set类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestSet {@Autowiredprivate RedisTemplate redisTemplate;/*** 存入值*/@Testpublic void setValue(){redisTemplate.boundSetOps("nameset").add("曹操");     redisTemplate.boundSetOps("nameset").add("刘备"); redisTemplate.boundSetOps("nameset").add("孙权");}/*** 提取值*/@Testpublic void getValue(){Set members = redisTemplate.boundSetOps("nameset").members();System.out.println(members);}/*** 删除集合中的某一个值*/@Testpublic void deleteValue(){redisTemplate.boundSetOps("nameset").remove("孙权");}/*** 删除整个集合*/@Testpublic void deleteAllValue(){redisTemplate.delete("nameset");}
}

1.5List类型操作

(1)右压栈

/*** 右压栈:后添加的对象排在后边*/
@Test
public void testSetValue1(){        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);
}

(2)左压栈

/*** 左压栈:后添加的对象排在前边*/
@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);
}

(3)根据索引查询元素

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

(4)移除某个元素的值

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

1.6Hash类型操作

(1)存入值

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

(2)提取所有的KEY

@Test
public void testGetKeys(){Set s = redisTemplate.boundHashOps("namehash").keys();     System.out.println(s);
}

运行结果:[a, b, c, d]

(3)提取所有的值

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

运行结果:[唐僧, 悟空, 八戒, 沙僧]

(4)根据KEY提取值

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

(5)根据KEY移除值

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

2.缓存广告数据

现在我们首页的广告每次都是从数据库读取,这样当网站访问量达到高峰时段,对数据库压力很大,并且影响执行效率。我们需要将这部分广告数据缓存起来。

2.1读取缓存

因为缓存对于我们整个的系统来说是通用功能。广告需要用,其它数据可能也会用到,所以我们将配置放在公共组件层(pinyougou-common)中较为合理。

配置可参照上文,配好后让pinyougou-content-service依赖pinyougou-common

修改 pinyougou-content-service的ContentServiceImpl

@Autowired
private RedisTemplate redisTemplate;@Override
public List<TbContent> findByCategoryId(Long categoryId) {List<TbContent> list = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);if(list==null) {System.out.println("从数据库读取数据放入缓存");TbContentExample example = new TbContentExample();Criteria criteria = example.createCriteria();criteria.andCategoryIdEqualTo(categoryId);criteria.andStatusEqualTo("1");//条件:有效example.setOrderByClause("sort_order");//排序list=contentMapper.selectByExample(example);redisTemplate.boundHashOps("content").put(categoryId, list);//存入缓存}else {System.out.println("从缓存读取数据");}return list;
}

2.2更新缓存

当广告数据发生变更时,需要将缓存数据清除,这样再次查询才能获取最新的数据

修改pinyougou-content-service工程ContentServiceImpl.java 的add方法

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

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

/*** 修改*/
@Override
public void update(TbContent content){//查询修改前的分类IdLong categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();redisTemplate.boundHashOps("content").delete(categoryId);contentMapper.updateByPrimaryKey(content);//如果分类ID发生了修改,清除修改后的分类ID的缓存if(categoryId.longValue()!=content.getCategoryId().longValue()){redisTemplate.boundHashOps("content").delete(content.getCategoryId());}
}

删除广告后清除缓存

    /*** 批量删除*/@Overridepublic void delete(Long[] ids) {for(Long id:ids){//清除缓存Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();//广告分类IDredisTemplate.boundHashOps("content").delete(categoryId);contentMapper.deleteByPrimaryKey(id);}
}

结语

对比数模学品优购真的是一种享受

WEB电商项目广告管理与缓存解决方案相关推荐

  1. 电商项目实战之缓存与Redis分布式锁

    电商项目实战之缓存与Redis分布式锁 缓存失效 缓存穿透 缓存雪崩 缓存击穿 分布式缓存 分布式锁 SpringBoot整合Redisson实现分布式锁 实现过程 缓存和数据库一致性 场景分析 解决 ...

  2. python电商项目源码_Python Django(WEB电商项目构建)

    (坚持每一天,就是成功) Python Django Web框架,Django是一个开放源代码的Web应用框架,由Python写成.采用了MTV的框架模式,即模型M,模板T和视图V组成. 安装Pyth ...

  3. 超详细测试项目——Web电商项目测试点整理.....

    虽然说近些年来,软件测试找工作的时候,简历中如果写着电商项目被认为是烂大街的项目,甚至受到根本不了解行情的HR或者部分公司的技术人员的刁难,但是:电商这么流行普遍的项目和应用,这不是很正常么! 毕竟全 ...

  4. 多用途的web电商项目网页模板源码下载

    Topico是清洁简洁的电子商务HTML5模板,可以作为任何在线商店超市,食品和饮料店,新鲜食品,有机食品,蔬菜店.100%网络响应设计,模板将让你的网站看起来更令人印象深刻,对访客的吸引力. 基于b ...

  5. Web实战——电商项目

    文章目录 电商项目实践 1 准备数据 模块说明 实践过程 相关技术 2 搭建 maven 私服(nexus) 模块说明 实践过程 相关技术 3 Dubbo 服务 模块说明 实践过程 相关技术 4 后台 ...

  6. 电商项目实战之分布式事务解决方案

    电商项目实战之分布式事务解决方案 本地事务 事务隔离级别 事务传播机制 分布式事务 CAP理论 选举与同步理论 BASE理论 解决方案 2PC模式(XA事务) 柔性事务-TCC事务补偿型方案 柔性事务 ...

  7. 电商项目相关面试问题及答案

    请描述一下这个系统? [回答技巧] 从3个方面来回答这个问题: |–系统背景及系统概述 |–系统包括的业务模块及主业务流程 |–责任模块 [回答示例] 第一个方面:系统背景及系统概述 优购时尚商城是香 ...

  8. 电商项目中的经典问题

    转载自:https://blog.csdn.net/A_BlackMoon/article/details/80094814 请描述一下这个系统? [回答技巧] 从3个方面来回答这个问题: |--系统 ...

  9. Java开发技术大杂烩(三)之电商项目优化、rabbitmq、Git、OSI、VIM、Intellj IDEA、HTTP、JS、Java...

    前言 最近公司让我维护Spring+Servlet+Hibernate+Spring Security+Jsp的老项目,正好可以锻炼我的业务逻辑和掌控项目的能力.虽然项目很老,但是其中还是有很多值我学 ...

最新文章

  1. CSLA .NET概述
  2. 堆晶结构_橄榄岩的特殊问题
  3. 【DP】[ZJOI2008][HYSBZ/BZOJ1037]生日聚会Party
  4. 前端模块化开发中webpack、npm、node、nodejs之间的关系[小白总结]
  5. 人的执念真的是非常的可怕
  6. linux——grep 文本过滤器
  7. 函数语法:Js之on和addEventListener的使用与不同
  8. 一些科研中经常用到的工具
  9. ArcGIS Maritime Server 开发教程(二)ArcGIS 海图软件系列
  10. word2vec 使用gensim训练词向量
  11. windows server2016 如何安装IIS
  12. Java、JSP大学生助学贷款管理系统的设计与实现
  13. 计算机信息中心的安全生产责任,信息中心安全生产责任制 (刘.doc
  14. 最性感的肩膀纹身设计女装 - 5令人惊叹的设计,你会爱!
  15. The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
  16. 《迅雷链精品课》第六课:主流区块链数据存储分析(一)
  17. MarkdownPad2 使用教程
  18. 六字诀教你辨肾脏是否健康
  19. 三菱4轴控制伺服案例,三菱PLC FX3U加三菱1PG定位模 块控制4个松下伺服,有完整的注释,结构清晰明了。伺服控制程序JOG HOME 定位 全部写成了功能块FB .你可以直接拿过去用
  20. java中上传本地图片

热门文章

  1. 社区外卖跑腿小程序怎么做?(拼团拼车模块+APP开发费用)
  2. Linux常用命令个人记录
  3. Struts原理与实践(7)
  4. 移动端名片识别SDK
  5. 我们应不应该继续学习python
  6. 蓝牙耳机哪个品牌性价比高?高性价比真无线蓝牙耳机
  7. Scrapy框架: 异常错误处理
  8. 芯片设计五部曲之一 | 声光魔法师——模拟IC
  9. 【SpringBoot】十八、拦截器 interceptor
  10. java练习-String类、StringBuilder类、StringBuffer类10