文章目录
一、对关键配置信息进行DES加密
1.1使用PropertyPlaceholderConfigurer实现对称加密
对jdbc中的jdbc.user和jdbc,password进行加密
首先就要编写一个工具类可以把明文转换成密文的类,然后把加密后的信息给替换掉。
然后在spring-dao.xml中进行配置解密,所以涉及到加密和解密的过程。
1.2使用DES进行加密以及代码实现
1.2.1DESUtil.javad的代码
其中有一个getinstance()方法的原因及作用看这个超链接
构造代码块,局部代码块和静态代码块的作用和区别
toString()方法返回对象本身
getBytes() 方法有两种形式:
getBytes(String charsetName): 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
getBytes(): 使用平台的默认字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
package com.imooc.o2o.util;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* des 是一种对称的加密算法,所谓对称加密算法即
* 加密和解密使用相同秘钥的算法
* @author acer
*
*/
public class DESUtil {
private static Key key;
// 设置密钥key
private static String KEY_STR = "myKey";
//编码规则
private static String CHARSETNAME = "UTF-8";
//算法
private static String ALGORITHM = "DES";
static {
try {
// 生成DES算法对象
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
// 运行SHA1安全策略
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
// 设置上密钥种子
secureRandom.setSeed(KEY_STR.getBytes());
// 初始化基于SHA1的算法对象
generator.init(secureRandom);
// 生成密钥对象
key = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取加密后的信息
*
* @param str 待加密字符串
* @return
*/
public static String getEncryptString(String str) {
// 基于BASE64编码,接收byte[]并转换为String
BASE64Encoder base64encoder = new BASE64Encoder();
try {
// 按UTF-8编码
byte[] bytes = str.getBytes(CHARSETNAME);
// 获取加密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化密码信息
cipher.init(Cipher.ENCRYPT_MODE, key);
// 加密
byte[] doFinal = cipher.doFinal(bytes);
// byte[] to encode好的String并返回
return base64encoder.encode(doFinal);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取解密之后的信息
*
* @param str 待解密字符串
* @return
*/
public static String getDecryptString(String str) {
// 基于BASE64编码,接收byte[]并转换为String
BASE64Decoder base64decoder = new BASE64Decoder();
try {
// 将字符串decode成byte[]
byte[] bytes = base64decoder.decodeBuffer(str);
// 获取解密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化解密信息
cipher.init(Cipher.DECRYPT_MODE, key);
// 解密
byte[] doFinal = cipher.doFinal(bytes);
// 返回解密之后的信息
return new String(doFinal, CHARSETNAME);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 测试
public static void main(String[] args) {
System.out.println(getEncryptString("123"));
System.out.println(getDecryptString("WnplV/ietfQ="));
}
}
1.3DES的解密以及EncryptPropertyPlaceholderConfigurer的代码及讲解
把加密后的数据写入到jdbc.property中只有进行解密后才能连接数据库,所以就要在spring-dao.xml进行改造,
以及编写一个类EncryptPropertyPlaceholderConfigurer以及部分的spring-dao.xml的代码
1.3.1EncryptPropertyPlaceholderConfigure的代码
这个类继承PropertyPlaceholderConfigurer,重写convertProperty,明确要加密的内容
package com.imooc.o2o.util;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* @Description: 继承PropertyPlaceholderConfigurer,重写convertProperty
*
*
*/
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
// 需要加密的字段数组
private String[] encryptPropNames = { "jdbc.user", "jdbc.password" };
/**
* 对关键的属性进行转换
*/
@Override
protected String convertProperty(String propertyName, String propertyValue) {
// 判断是否加密
if (isEncryptProp(propertyName)) {
// 解密
String decryptValue = DESUtil.getDecryptString(propertyValue);
return decryptValue;
} else {
return propertyValue;
}
}
/**
* 判断该属性是否加密
*
* @param propertyName
* @return
*/
private boolean isEncryptProp(String propertyName) {
for (String encryptpropertyName : encryptPropNames) {
if (encryptpropertyName.equals(propertyName))
return true;
}
return false;
}
}
1.3.2spring-dao.xml的部分代码
<bean class="com.imooc.o2o.util.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"></property>
</bean>
二、缓存技术之理论讲解
2.1redis和jedis的用法以及区别
2.2Redis配置(redis客户端 jedis,服务于java)
2.2.1在pom.xml中引入redis客户端jedis
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.2.2由于是基于ssm的框架,还要进行spring-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:context="http://www.springframework.org/schema/context"
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">
<!-- Redis连接池的设置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 控制一个pool可分配多少个jedis实例 -->
<property name="maxTotal" value="${redis.pool.maxActive}" />
<!-- 连接池中最多可空闲maxIdle个连接 ,这里取值为20,表示即使没有数据库连接时依然可以保持20空闲的连接,而不被清除,随时处于待命状态。 -->
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<!-- 最大等待时间:当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计数),超过时间则抛出异常 -->
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<!-- 在获取连接的时候检查有效性 -->
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<!-- 创建Redis连接池,并做相关配置 -->
<bean id="jedisWritePool" class="com.imooc.o2o.cache.JedisPoolWriper"
depends-on="jedisPoolConfig">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="${redis.hostname}" />
<constructor-arg index="2" value="${redis.port}" type="int" />
</bean>
<!-- 创建Redis工具类,封装好Redis的连接以进行相关的操作 -->
<bean id="jedisUtil" class="com.imooc.o2o.cache.JedisUtil" scope="singleton">
<property name="jedisPool">
<ref bean="jedisWritePool" />
</property>
</bean>
<!-- Redis的key操作 -->
<bean id="jedisKeys" class="com.imooc.o2o.cache.JedisUtil$Keys"
scope="singleton">
<!-- <constructor-arg ref="jedisUtil"></constructor-arg> -->
</bean>
<!-- Redis的Strings操作 -->
<bean id="jedisStrings" class="com.imooc.o2o.cache.JedisUtil$Strings"
scope="singleton">
<!-- <constructor-arg ref="jedisUtil"></constructor-arg> -->
</bean>
<!-- Redis的Lists操作 -->
<bean id="jedisLists" class="com.imooc.o2o.cache.JedisUtil$Lists"
scope="singleton">
<!-- <constructor-arg ref="jedisUtil"></constructor-arg> -->
</bean>
<!-- Redis的Sets操作 -->
<bean id="jedisSets" class="com.imooc.o2o.cache.JedisUtil$Sets"
scope="singleton">
<!-- <constructor-arg ref="jedisUtil"></constructor-arg> -->
</bean>
<!-- Redis的HashMap操作 -->
<bean id="jedisHash" class="com.imooc.o2o.cache.JedisUtil$Hash"
scope="singleton">
<!-- <constructor-arg ref="jedisUtil"></constructor-arg> -->
</bean>
</beans>
2.2.3redis的一些常用属性的配置redis.properties
#你买的云服务器的地址
redis.hostname=***********
#端口号
redis.port=6379
redis.database=0
redis.pool.maxActive=60
redis.pool.maxIdle=30
redis.pool.maxWait=3000
redis.pool.testOnBorrow=true
在web.xml中的configlocation中能读到spring的数据,要想redis.properties的配置在spring-redis.xml中使用需要在spring.dao的中加入配置
<bean class="com.imooc.o2o.util.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>//这里是配置数据库的时候加入的
<value>classpath:redis.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"></property>
</bean>
2.3Jedis基本通用函数配置及使用
2.3.1创建Redis连接池,并做相关配置
JedisPoolWriper的代码编写,指定redis的jedisPool接口构造函数,这样才能在centos成功创建jedispool
package com.imooc.o2o.cache;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisPoolWriper {
/*redis连接池对象*/
private JedisPool jedisPool;
//里面的参数是spring-redis.xml中传入进来的
public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host, final int port) {
try {
jedisPool = new JedisPool(poolConfig, host, port);
} catch (Exception e) {
e.printStackTrace();
}
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
}
2.3.2创建Redis工具类,封装好redis的连接以进行相关的操作&&&这里有一个JedisUtil的工具类来配合spring-redis.xm(代码很多了解就好)
三、缓存技术之编码实现
由于区域信息,头条信息,店铺类别信息不经常使用,所以要把这三个service层的方法进行改造,让他加入redis缓存,也就是java的jedis缓存
3.1区域信息的改造
3.1.1区域信息service层改造
AreaService的改造后的代码
package com.imooc.o2o.service;
import java.util.List;
import com.imooc.o2o.entity.Area;
public interface AreaService {
public static final String AREALISTKEY="arealist";
List<Area> getAreaList();
}
3.1.1区域信息service层的实现改造
AreaServiceImpl的改造后的代码
package com.imooc.o2o.service.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.cache.JedisUtil;
import com.imooc.o2o.dao.AreaDao;
import com.imooc.o2o.entity.Area;
import com.imooc.o2o.exceptions.AreaOperationException;
@Service
public class AreaServiceImpl implements com.imooc.o2o.service.AreaService{
@Autowired
private AreaDao areaDao;
@Autowired
private JedisUtil.Keys jedisKeys;
@Autowired
private JedisUtil.Strings jedisStrings;
private static Logger logger = LoggerFactory.getLogger(AreaServiceImpl.class);
@Override
@Transactional
public List<Area> getAreaList() {
// key
String key = AREALISTKEY;
List<Area> areaList = null;
ObjectMapper mapper = new ObjectMapper();
// 如果Redis中未存在key
if (!jedisKeys.exists(key)) {
// 数据库中获取区域列表
areaList = areaDao.queryArea();
String jsonString = null;
// 将list转换为String
try {
jsonString = mapper.writeValueAsString(areaList);
} catch (JsonProcessingException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new AreaOperationException(e.getMessage());
}
jedisStrings.set(key, jsonString);
}
// Redis中存在key,则取出
else {
// 将String转换为List
String jsonString = jedisStrings.get(key);
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Area.class);
try {
areaList=mapper.readValue(jsonString, javaType);
} catch (JsonParseException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new AreaOperationException(e.getMessage());
} catch (JsonMappingException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new AreaOperationException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new AreaOperationException(e.getMessage());
}
}
return areaList;
}
}
3.2头条信息的改造
3.2.1头条信息service层改造
HeadLineService改造后的代码
package com.imooc.o2o.service;
import java.io.IOException;
import java.util.List;
import com.imooc.o2o.entity.HeadLine;
public interface HeadLineService {
public static final String HLLISTKEY="headlinelist";
/**
* 根据条件查询头条列表
*
* @param headLineCondition
* @return
* @throws IOException
*/
List<HeadLine> getHeadLineList(HeadLine headLineCondition) throws IOException;
}
3.2.1头条信息service层的实现改造
HeadLineServiceImpl改造后的代码
package com.imooc.o2o.service.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.cache.JedisUtil;
import com.imooc.o2o.dao.HeadLineDao;
import com.imooc.o2o.entity.HeadLine;
import com.imooc.o2o.exceptions.HeadLineOperationException;
import com.imooc.o2o.service.HeadLineService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.o2o.util.PathUtil;
/**
* @Description: 首页头条业务接口实现
*
*/
@Service
public class HeadLineServiceImpl implements HeadLineService {
@Autowired
private JedisUtil.Strings jedisStrings;
@Autowired
private JedisUtil.Keys jedisKeys;
@Autowired
private HeadLineDao headLineDao;
private static Logger logger = LoggerFactory.getLogger(HeadLineServiceImpl.class);
@Override
@Transactional
public List<HeadLine> getHeadLineList(HeadLine headLineCondition) {
//定义接收对象
List<HeadLine> headLineList = null;
//定义Jackson数据转换操作类
ObjectMapper mapper = new ObjectMapper();
//定义redis的key前缀
String key = HLLISTKEY;
//拼接出redis的key
if (headLineCondition != null && headLineCondition.getEnableStatus() != null) {
key = key + "_" + headLineCondition.getEnableStatus();
}
// redis中不存在key,则设值
if (!jedisKeys.exists(key)) {
//若不存在,则从数据库里面取出相应数据
headLineList = headLineDao.queryHeadLine(headLineCondition);
// 将相关的实体类集合转换成string,存入redis里面对应的key中
String jsonString;
try {
jsonString = mapper.writeValueAsString(headLineList);
jedisStrings.set(key, jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new HeadLineOperationException(e.getMessage());
}
} else {
String jsonString = jedisStrings.get(key);
// 将jsonString转为list
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, HeadLine.class);
try {
headLineList = mapper.readValue(jsonString, javaType);
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new HeadLineOperationException(e.getMessage());
}
}
return headLineList;
}
}
3.3店铺类别信息的改造
3.3.1店铺类别信息service层改造
ShopCategoryService改造后的代码
package com.imooc.o2o.service;
import java.util.List;
import com.imooc.o2o.entity.ShopCategory;
public interface ShopCategoryService {
public static final String SCLISTKEY="shopcategorylist";
/**
* 根据查询条件获取shopCategory列表
* @param shopCategoryCondition
* @return
*/
List<ShopCategory> getShopCategoryList(ShopCategory shopCategoryCondition);
}
3.3.1店铺类别信息service层的实现改造
ShopCategoryServiceImpl改造后的代码
package com.imooc.o2o.service.impl;
/*import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imooc.o2o.dao.ShopCategoryDao;
import com.imooc.o2o.entity.ShopCategory;
import com.imooc.o2o.service.ShopCategoryService;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.o2o.cache.JedisUtil;
import com.imooc.o2o.dao.ShopCategoryDao;
import com.imooc.o2o.entity.ShopCategory;
import com.imooc.o2o.exceptions.ShopCategoryOperationException;
import com.imooc.o2o.service.ShopCategoryService;
/**
* @Description: 店鋪类别业务接口实现类
*
*/
@Service
public class ShopCategoryServiceImpl implements ShopCategoryService {
@Autowired
private ShopCategoryDao shopCategoryDao;
@Autowired
private JedisUtil.Strings jedisStrings;
@Autowired
private JedisUtil.Keys jedisKeys;
private static Logger logger = LoggerFactory.getLogger(ShopCategoryServiceImpl.class);
@Override
public List<ShopCategory> getShopCategoryList(ShopCategory shopCategoryCondition) {
// 定义Redis的key前缀
String key = SCLISTKEY;
// 定义接收对象
List<ShopCategory> shopCategories = null;
// 定义jackson数据转换操作类
ObjectMapper mapper = new ObjectMapper();
// 拼接出redis的key
if (shopCategoryCondition == null) {
// 若查询条件为空,则列出所有首页大类,即parentId为空的店铺类型
key = key + "_allfirstlevel";
} else if (shopCategoryCondition != null && shopCategoryCondition.getParent() != null
&& shopCategoryCondition.getParent().getShopCategoryId() != null) {
// 若parentId不为空,则列出该parentId下的所有子类别
key = key + "_parent" + shopCategoryCondition.getParent().getShopCategoryId();
} else if (shopCategoryCondition != null) {
// 列出所有子类别,不管其属于哪个类都列出
key = key + "_allsecondlevel";
}
// 判断key是否存在
if (!jedisKeys.exists(key)) {
// 若不存在,则从数据库中取出数据
shopCategories = shopCategoryDao.queryShopCategory(shopCategoryCondition);
// 将实体类集合转换为string,存入redis
String jsonString = null;
try {
jsonString = mapper.writeValueAsString(shopCategories);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new ShopCategoryOperationException(e.getMessage());
}
jedisStrings.set(key, jsonString);
} else {
// 若存在,则直接从redis中取出数据
String jsonString = jedisStrings.get(key);
// 将String转换为集合类型
JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, ShopCategory.class);
try {
shopCategories = mapper.readValue(jsonString, javaType);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new ShopCategoryOperationException(e.getMessage());
}
}
return shopCategories;
}
}
3.4根据key前缀匹配原则删除缓存数据
$emsp;编写一个类删除redis里面的缓存的数据
3.4.1CacheService的代码
package com.imooc.o2o.service;
public interface CacheService {
/**
* 依据key前缀匹配原则删除缓存数据
*
* @param keyPrefix
*/
void removeFromCache(String keyPrefix);
}
3.4.2CacheServiceImpl的代码
package com.imooc.o2o.service.impl;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.imooc.o2o.cache.JedisUtil;
import com.imooc.o2o.service.CacheService;
@Service
public class CacheServiceImpl implements CacheService{
@Autowired
private JedisUtil.Keys jedisKeys;
@Override
public void removeFromCache(String keyPrefix) {
Set<String> keySet = jedisKeys.keys(keyPrefix + "*");
for (String key : keySet) {
jedisKeys.del(key);
}
}
}