
概述
本篇将介绍如下几个方面:
完成运营商后台广告类型管理与广告管理、完成前台工程广告轮播图的展示、使用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>
<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接口增加方法定义
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 {
@Reference
private ContentService contentService;
@RequestMapping("/findByCategoryId")
public List<TbContent> findByCategoryId(Long categoryId) {
return contentService.findByCategoryId(categoryId);
}
}
2.3前端代码
在pinyougou-portal-web工程创建contentService.js
app.service("contentService",function($http){
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">
<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" />
<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 {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void setValue(){
redisTemplate.boundValueOps("name").set("itcast");
}
@Test
public void getValue(){
String str = (String) redisTemplate.boundValueOps("name").get();
System.out.println(str);
}
@Test
public void deleteValue(){
redisTemplate.delete("name");;
}
}
1.4Set类型操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class TestSet {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void setValue(){
redisTemplate.boundSetOps("nameset").add("曹操");
redisTemplate.boundSetOps("nameset").add("刘备");
redisTemplate.boundSetOps("nameset").add("孙权");
}
@Test
public void getValue(){
Set members = redisTemplate.boundSetOps("nameset").members();
System.out.println(members);
}
@Test
public void deleteValue(){
redisTemplate.boundSetOps("nameset").remove("孙权");
}
@Test
public 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){
Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.updateByPrimaryKey(content);
if(categoryId.longValue()!=content.getCategoryId().longValue()){
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
}
删除广告后清除缓存
@Override
public void delete(Long[] ids) {
for(Long id:ids){
Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.deleteByPrimaryKey(id);
}
}
结语
对比数模学品优购真的是一种享受🤔
👴不想回建模了,拜拜了您嘞