PYG电商项目开发 -- day06 内容操作、spring-data-redis的使用

一、内容管理准备工作


1、将代码生成器生成的Content*.java和ContentCate*.java拷入对应的文件夹下




2、将生成的js文件拷入mamager-web项目中




3、实现广告分类管理的列表


(1)、content_category.html




4、实现广告数据的维护


(1)、springmvc.xml和application.properties以及fdfs_client.conf




	<!-- 图片上传配置 -->
	<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>


IMAGE_SERVER_URL=http://192.168.25.133/


tracker_server=192.168.25.133:22122


(2)、content.html




(3)、contentController.js


//控制层 
app.controller('contentController', function($scope, $controller,
		contentCategoryService, uploadService, contentService) {

	$controller('baseController', {
		$scope : $scope
	});// 继承

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

	// 上传图片
	$scope.uploadFile = function(){
		uploadService.uploadFile().success(function(data){
			if(data.success){
				$scope.entity.pic = data.message;
			}else{
				alert("上传失败");
			}
		});
	}

	// 页面初始化查询所有分类的方法
	$scope.findAllCategoryList = function() {
		contentCategoryService.findAll().success(function(data) {
			$scope.categoryList = data;
		});
	}

	// 定义reloadList重新加载列表的方法
	$scope.reloadList = function() {
		var page = $scope.paginationConf.currentPage;
		var pageSize = $scope.paginationConf.itemsPerPage;
		$scope.search(page, pageSize, $scope.searchEntity);
	}


(4)、uploadService.js


/*图片上传的service层代码*/
app.service("uploadService", function($http){
	
	//定义图片上传的方法
	this.uploadFile = function(){
		//angularjs上传文件的方法
		var formData = new FormData();
		
		//获取表单中的类型是file的对象,添加到创建的表单对象中
		formData.append("file", file.files[0]);
		
		return $http({
			method:"post",
			data:formData,
			url:"../upload.do",
			headers:{'Content-Type': undefined},
			transformRequest: angular.identity
		});
	}
});


(5)、UploadController.java


package com.pinyougou.manager.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.resultentity.ResultMessage;

import utils.FastDFSClient;

@RestController
public class UploadController {

	// 从properties文件中获取图片服务器地址
	@Value("${IMAGE_SERVER_URL}")
	private String imageServerUrl;

	@RequestMapping("/upload")
	public ResultMessage uploadFile(MultipartFile file) {
		FastDFSClient fastDFSClient;
		try {
			fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
			// 获取源文件名
			String originalFilename = file.getOriginalFilename();
			// 扩展名截取
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			// 上传图片,并返回上传后的地址
			String uploadFile = fastDFSClient.uploadFile(file.getBytes(), extName);
			// uploadFile:group1/M00/00/00/wKgZhVsCRciAfmNFAACuI4TeyLI361.jpg
			return new ResultMessage(true, imageServerUrl + uploadFile);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultMessage(false, "上传失败");
		}

	}
}


二、构建门户网站相关项目


1、pinyougou-protal-web


依照pinyougou-manager-web项目进行配置(不需要spring-security)


2、导入门户网站静态资源文件






三、门户网站相关操作


1、显示门户网站banner(轮播图)数据


(1)、index.html




(2)、base.js


/* 该文件是基本自定义模块文件,不需要引入任何的模块*/
var app = angular.module("pinyougou", []);


(3)、indexController.js


app.controller("indexController",function($scope, contentService){
	
	//获取所有广告列表
	$scope.findAllBannerList = function(){
		contentService.findByCategoryId(1).success(function(data){
			$scope.bannerList = data;
		});
	}
});


(4)、contentService.js


//服务层
app.service('contentService', function($http) {

	// 读取列表数据绑定到表单中
	this.findByCategoryId = function(categoryId) {
		return $http.get('../content/findByCategoryId.do?categoryId='
				+ categoryId);
	}

});


(5)、IndexController.java


package com.pinyougou.portal.controller;

import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.pojo.TbContent;
import com.pinyougou.sellergoods.service.ContentService;

@RestController
@RequestMapping("/content")
public class ContentController {
	
	@Reference
	private ContentService contentService;

	/**
	 * 根据id查询所有广告列表
	 * 
	 * @param categoryId
	 * @return
	 */
	@RequestMapping("/findByCategoryId")
	public List<TbContent> findByCategoryId(Long categoryId) {
		return contentService.findByCategoryId(categoryId);

	}
}


2、spring-data-redis的使用介绍


(1)、虚拟机中redis安装


详情请见:https://blog.csdn.net/wingzhezhe/article/category/6948969


(2)、pinyougou-common项目中加入spring-data-redis使用所需的jar包


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


(3)、加入redis配置配置文件




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>  


redis-config.properties


# Redis settings 
# server IP 
redis.host=192.168.25.128 
# server port 
redis.port=6379
# server pass 
redis.pass=
# use dbIndex 
redis.database=0
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例 
redis.maxIdle=300
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;  
redis.maxWait=3000
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的  
redis.testOnBorrow=true


(4)、测试hash类型数据


package com.pinyougou.test;

import java.util.Set;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class HashTestDemo {
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Test
	public void add() {
		redisTemplate.boundHashOps("testHash").put("a", "AAA");
		redisTemplate.boundHashOps("testHash").put("b", "BBB");
	}
	
	@Test
	public void get() {
		Set keys = redisTemplate.boundHashOps("testHash").keys();
		for (Object key : keys) {
			System.out.println(key);
			System.out.println(redisTemplate.boundHashOps("testHash").get(key));
		}
	}
	
	@Test
	public void del() {
		redisTemplate.boundHashOps("testHash").delete("a");
		redisTemplate.delete("testHash");
	}
	
	

}


(5)、测试List类型数据


package com.pinyougou.test;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class ListTestDemo {
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Test
	public void add() {
		redisTemplate.boundListOps("testList").leftPush("张三");
		redisTemplate.boundListOps("testList").leftPush("李四");
		redisTemplate.boundListOps("testList").leftPush("王武");
		redisTemplate.boundListOps("testList").leftPush("赵柳");
	}
	
	@Test
	public void get() {
		List list = redisTemplate.boundListOps("testList").range(0, 10);
		for (Object object : list) {
			System.out.println(object);
		}
	}
	
	@Test
	public void del() {
		redisTemplate.boundListOps("testList").remove(1, "张三");
		redisTemplate.delete("testList");
	}

}


(6)、测试Set类型数据


package com.pinyougou.test;

import java.util.Set;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class SetTestDemo {
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Test
	public void add() {
		redisTemplate.boundSetOps("testSet").add("张三");
		redisTemplate.boundSetOps("testSet").add("李四");
		redisTemplate.boundSetOps("testSet").add("王武");
		redisTemplate.boundSetOps("testSet").add("赵柳");
	}
	
	@Test
	public void get() {
		Set set = redisTemplate.boundSetOps("testSet").members();
		for (Object object : set) {
			System.out.println(object);
		}
	}
	
	@Test
	public void del() {
		redisTemplate.delete("testSet");
	}

}


(7)、测试value类型数据


package com.pinyougou.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/applicationContext-redis.xml")
public class VlueTestDemo {

	@Autowired
	private RedisTemplate redisTemplate;
	
	@Test
	public void add() {
		redisTemplate.boundValueOps("username").set("Jerry");
	}
	
	@Test
	public void get() {
		System.out.println(redisTemplate.boundValueOps("username").get());
	}
	
	@Test
	public void del() {
		redisTemplate.delete("username");
	}
}


3、从redis中获取广告轮播图数据


(1)、改造ContentServiceImpl.java


	/**
	 * 根据id查询广告列表
	 */
	public List<TbContent> findByCategoryId(Long categoryId) {

		// 先从redis中获取广告信息
		List<TbContent> contentList = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);
		if(contentList == null) {
			//redis中没有获取到数据,查询数据库
			System.out.println("从数据库查");
			TbContentExample example = new TbContentExample();
			Criteria criteria = example.createCriteria();
			criteria.andCategoryIdEqualTo(categoryId);
			criteria.andStatusEqualTo("1");// 添加是否有效的条件
			example.setOrderByClause("sort_order");
			contentList = contentMapper.selectByExample(example);
			//将数据库中查询的数据放入redis中
			redisTemplate.boundHashOps("content").put(categoryId, contentList);
		}else {
			System.out.println("从redis查");
		}
		return contentList;
	}


4、实现修改广告数据后同步更新redis中数据


ContentServiceImpl.java


	/**
	 * 增加
	 */
	@Override
	public void add(TbContent content) {
		contentMapper.insert(content);
		// 修改redis中的数据
		redisTemplate.boundHashOps("content").delete(content.getCategoryId());
	}
	
	/**
	 * 批量删除
	 */
	@Override
	public void delete(Long[] ids) {
		for (Long id : ids) {
			contentMapper.deleteByPrimaryKey(id);
			//删除redis中对应的类别的数据
			Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();
			redisTemplate.boundHashOps("content").delete(categoryId);
		}
	}

	/**
	 * 修改
	 */
	@Override
	public void update(TbContent content) {
		TbContent tbContent = contentMapper.selectByPrimaryKey(content.getId());
		// 获取原来的分类id
		Long oldCategoryId = tbContent.getCategoryId();
		// 获取从页面传递过来的分类id
		Long newCategoryId = content.getCategoryId();
		// 修改数据库
		contentMapper.updateByPrimaryKey(content);
		// 更新redis中对应的数据
		redisTemplate.boundHashOps("content").delete(newCategoryId);
		if (oldCategoryId.longValue() != newCategoryId.longValue()) {
			redisTemplate.boundHashOps("content").delete(oldCategoryId); 
		}
	}


猜你喜欢

转载自blog.csdn.net/wingzhezhe/article/details/80651702