2020-11-20_项目常用工具类
-
Redis
package cn.itsource.util; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * 整个单例: 枚举限制实例只有一个就是单例 */ public enum JedisUtil { INSTANCE; private static JedisPool pool = null; static { //1 创建连接池配置对象 JedisPoolConfig config = new JedisPoolConfig(); //2 对连接池配置对象进行配置 config.setMaxIdle(2);//最小连接数 config.setMaxTotal(10);//最大连接数 config.setMaxWaitMillis(2*1000);//超时时间 config.setTestOnBorrow(true);//测试连接是否畅通时机 //3 通过配置对象创建连接池对象 //正常来说应该配置到properties pool = new JedisPool(config,"127.0.0.1",6379,2*1000,"123456"); } //获取连接 public Jedis getResource(){ return pool.getResource(); } //释放连接 public void release(Jedis jedis){ if (jedis != null) { jedis.close(); } } //常用操作封装到里面 设置字符串 获取字符串 设置字符串并添加超时时间 public void set(String key,String val){ Jedis jedis = null; try { jedis = this.getResource(); jedis.set(key,val); } catch (Exception e) { e.printStackTrace(); }finally { this.release(jedis); } } public void set(String key,String val,int seconds){ Jedis jedis = null; try { jedis = this.getResource(); //设置值时设置超时时间 jedis.setex(key,seconds,val); } catch (Exception e) { e.printStackTrace(); }finally { this.release(jedis); } } public String get(String key){ Jedis jedis = null; try { jedis = this.getResource(); return jedis.get(key); } catch (Exception e) { e.printStackTrace(); }finally { this.release(jedis); } return null; } }
-
Springboot Spring data redis
<!--spirngboot springdata对redis支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
redis相关配置
# redis 属性信息 ## redis数据库索引(默认为0) spring.redis.database=0 ## redis服务器地址 spring.redis.host=localhost ## redis服务器连接端口 spring.redis.port=6379 ## redis服务器连接密码(默认为空) spring.redis.password=123456 ## 连接池最大连接数(使用负值表示没有限制) spring.redis.jedis.pool.max-active=8 ## 连接池中的最大空闲连接 spring.redis.jedis.pool.max-idle=8 ## 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait=-1ms ## 连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=0
-
-
图片上传:FastDFS(分布式文件系统)
-
创建Maven工程fastDFSdemo
<!-- https://mvnrepository.com/artifact/cn.bestwu/fastdfs-client-java --> <dependency> <groupId>cn.bestwu</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27</version> </dependency>
-
添加配置文件fdfs_client.conf ,将其中的服务器地址设置为
***\*tracker_server\****=115.159.217.249:22122
-
创建java类,main方法代码如下:
// 1、加载配置文件,配置文件中的内容就是 tracker 服务的地址。 ClientGlobal.init("D:/maven_work/fastDFS-demo/src/fdfs_client.conf"); // 2、创建一个 TrackerClient 对象。直接 new 一个。 TrackerClient trackerClient = new TrackerClient(); // 3、使用 TrackerClient 对象创建连接,获得一个 TrackerServer 对象。 TrackerServer trackerServer = trackerClient.getConnection(); // 4、创建一个 StorageServer 的引用,值为 null StorageServer storageServer = null; // 5、创建一个 StorageClient 对象,需要两个参数 TrackerServer 对象、StorageServer 的引用 StorageClient storageClient = new StorageClient(trackerServer, storageServer); // 6、使用 StorageClient 对象上传图片。 //扩展名不带“.” String[] strings = storageClient.upload_file("D:/pic/benchi.jpg", "jpg", null); // 7、返回数组。包含组名和图片的路径。 for (String string : strings) { System.out.println(string); }
-
后台代码
@RestController @RequestMapping("/dfs") public class FastDfsController { @PostMapping public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){ try { System.out.println(file.getOriginalFilename() + ":" + file.getSize()); String originalFilename = file.getOriginalFilename(); // xxx.jpg String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1); System.out.println(extName); String filePath = FastDfsUtil.upload(file.getBytes(), extName); return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去 } catch (IOException e) { e.printStackTrace(); return AjaxResult.me().setSuccess(false).setMessage("上传失败!"+e.getMessage()); } } /** * 参数:完整路径 /goup1/xxxxx/yyyy * 返回值:成功与否,还要返回地址 * */ @DeleteMapping public AjaxResult del(@RequestParam(required = true,value = "path") String path){ String pathTmp = path.substring(1); // goup1/xxxxx/yyyy String groupName = pathTmp.substring(0, pathTmp.indexOf("/")); //goup1 String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy System.out.println(groupName); System.out.println(remotePath); FastDfsUtil.delete(groupName, remotePath); return AjaxResult.me(); } }
-
-
发送邮件
-
导包jar包
<!--对邮件的支持jar--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
配置文件
=======application.properties======= # 设置邮箱主机(服务商) spring.mail.host=smtp.qq.com # 设置用户名 spring.mail.username=64009120@qq.com # 设置密码,该处的密码是QQ邮箱开启SMTP的授权码而非QQ密码 spring.mail.password=qzbxiwjfrweecacf # 必须进行授权认证,它的目的就是阻止他人任意乱发邮件 spring.mail.properties.mail.smtp.auth=true #SMTP加密方式:连接到一个TLS保护连接 spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true =======application.yml======= mail: host: smtp.qq.com username: 64009120@qq.com password: qzbxiwjfrweecacf
-
发送简单邮件
@SpringBootTest @RunWith(SpringJUnit4ClassRunner.class) public class EmailTest { @Autowired private JavaMailSender javaMailSender; @Test public void send(){ SimpleMailMessage mailMessage = new SimpleMailMessage(); //设置发送人 mailMessage.setFrom("64009120@qq.com"); //邮件主题 mailMessage.setSubject("新型冠状病毒防护指南"); //邮件内容 mailMessage.setText("好好在家待着....."); //收件人 mailMessage.setTo("64009120@qq.com"); javaMailSender.send(mailMessage); } }
-
发送复杂邮件
@Test public void test2() throws Exception{ //创建复杂邮件对象 MimeMessage mimeMessage = javaMailSender.createMimeMessage(); //发送复杂邮件的工具类 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8"); helper.setFrom("64009120@qq.com"); helper.setSubject("新型冠状病毒防护指南"); http://img30.360buyimg.com/popWaterMark/jfs/t1/67988/7/14094/232759/5db64acfE6ab2b09e/38b5cb3dc38b4b1f.jpg" helper.setText("<h1>新型冠状病毒防护守则</h1>"+ "<img src='http://img30.360buyimg.com/popWaterMark/jfs/t1/67988/7/14094/232759/5db64acfE6ab2b09e/38b5cb3dc38b4b1f.jpg\"' />",true); //添加附件 helper.addAttachment("罗宾.jpg",new File("C:\\Users\\hm\\Desktop\\work\\aa.jpg")); helper.addAttachment("压缩文件", new File("C:\\Users\\hm\\Desktop\\20191010\\2020-02-05-智能商贸-DAY4\\resources\\resources.zip")); //收件人 helper.setTo("2518743821@qq.com"); javaMailSender.send(mimeMessage); }
-
-
Md5技术
-
不可逆加密技术,只能加密不能解密。 只能做比对,一般用来加密用户登录密码。
我们要做的是把传入进行加密和数据库查询出来密文进行比对判断密码是否正确。
-
盐值:同一种加密算法,由于不同的盐值,加密出来就不一样。
1) 整个系统使用同一个盐值,多个用户共用-定义一个常量
2) 每个用户都有自己盐值,就算是相同的密码,两个用用户加密出来也不一样。
-
工具类
package cn.itsource.basic.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Utils { /** * 加密 * @param context */ public static String encrypByMd5(String context) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(context.getBytes());//update处理 byte [] encryContext = md.digest();//调用该方法完成计算 int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < encryContext.length; offset++) {//做相应的转化(十六进制) i = encryContext[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static void main(String[] args) { //加密 //1 生成随机盐值 String pwd = "1"; String salt = StrUtils.getComplexRandomString(32); //2 通过这个盐值加密 String md5Pwd = MD5Utils.encrypByMd5(pwd +"yhp"+ salt+"xxxx"); System.out.println(md5Pwd); //密码比对 //1 查询盐值-就是salt String saltTmp = salt; //3 加密比对 String pwdTmp = "1"; String inputMd5Pwd = MD5Utils.encrypByMd5(pwdTmp +"yhp"+ saltTmp+"xxxx"); if (inputMd5Pwd.equals(md5Pwd)){ System.out.println("登录成功!"); }else{ System.out.println("密码错误"); } } }
-
-
注册实现-发送短信验证码
-
短信jar包
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
-
中国网建短信接口
===============定义常量================= package cn.itsource.basic.util; /** * 短信常量类 */ public class SmsContants { //用户名 public static final String UID = "xxx"; //秘钥 public static final String KEY = "yyyy"; } =================定义短信工具接口===================== package cn.itsource.basic.util; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; /** * 短信发送工具类 */ public class SmsUtil { /** * 发送短信 * @param phones 手机们 a,b * @param content 发送内容 * @return 返回值 */ public static String sendSms(String phones,String content){ PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("http://utf8.api.smschinese.cn"); post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码 NameValuePair[] data ={ new NameValuePair("Uid", SmsContants.UID), new NameValuePair("Key", SmsContants.KEY), new NameValuePair("smsMob",phones), new NameValuePair("smsText",content)}; post.setRequestBody(data); client.executeMethod(post); int statusCode = post.getStatusCode(); System.out.println("statusCode:"+statusCode); //200 404 400 String result = new String(post.getResponseBodyAsString().getBytes("utf8")); return result; } catch (Exception e) { e.printStackTrace(); } finally { if (post != null) { post.releaseConnection(); } } return null; } public static void main(String[] args) { System.out.println(SmsUtil .sendSms("13330964748", "您的验证码为:8848")); } }
-
-
验证码流程图
e.printStackTrace(); } finally { if (post != null) { post.releaseConnection(); } } return null; } public static void main(String[] args) { System.out.println(SmsUtil .sendSms("13330964748", "您的验证码为:8848")); }
}
-
验证码流程图