Halo(一)
@EnableJpaAuditing 审计功能(启动类配置)
在实际的业务系统中,往往需要记录表数据的创建时间、创建人、修改时间、修改人。
每次手动记录这些信息比较繁琐,SpringDataJpa 的审计功能可以帮助我们来做这些繁琐的配置。
1. 在 spring jpa 中,支持在字段或者方法上进行注解:
@CreatedDate、@CreatedBy、
@LastModifiedDate、@LastModifiedBy
@CreatedDate:
表示该字段为创建时间时间字段,在这个实体被insert的时候,会设置值
@CreatedBy:
表示该字段为创建人,在这个实体被insert的时候,会设置值
2. 在类上加上注解 @EntityListeners(AuditingEntityListener.class)
3. 在 application启动类 中加上注解 @EnableJpaAuditing
4. 这个时候,在jpa的save方法被调用的时候,时间字段会自动设置并插入数据库,
但是CreatedBy和LastModifiedBy并没有赋值,因为需要实现AuditorAware接口来返回你需要插入的值。
@Configuration //使用jpa审计功能,保存数据时自动插入创建人id和更新人id
public class UserAuditorAware implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
//从session中获取当前登录用户的id
Long userId = 2L;
return Optional.of(userId);
}
}
@EnableScheduling 定时任务(启动类配置)
1. 在 application 启动类中加上注解 @EnableScheduling 开启对定时任务的支持。
2. 在相应的方法上添加 @Scheduled 声明需要执行的定时任务。
@Component
public class SchedulingConfig {
//设置每5秒执行一次。或者:@Scheduled(fixedRate = 5000,initialDelay = 0)
@Scheduled(cron = "0/5 * * * * ?")
public void getToken() {
System.Out.printf("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@EnableAsync 多线程支持(启动类配置)
SpringBoot 提供了注解 @EnableAsync + @Async 实现方法的异步调用。
1. 在启动类上加上 @EnableAsync 注解开启项目的异步调用功能。
2. 在需异步调用的方法上加上注解 @Async 即可实现方法的异步调用。
异步的方法有3种
1. 最简单的异步调用,返回值为void
2. 带参数的异步调用,异步方法可以传入参数
3. 异步调用返回Future
@Component
public class AsyncTask {
@Async
public Future<String> task() throws InterruptedException{
Thread.sleep(1000);
return new AsyncResult<String>("task执行完毕");
}
}
@RestController
public class AsyncTaskController {
@Autowired
private AsyncTask asyncTask;
@RequestMapping("/")
public String doTask() throws InterruptedException{
Future<String> task = asyncTask.task();
return task.get();
}
}
@EnableJpaRepositories 用来扫描和发现指定包及其子包中的Repository定义(启动类配置)
简单配置,格式如下:
@EnableJpaRepositories("repository")
配置支持多个package,格式如下:
@EnableJpaRepositories({"repository1", "repository2"})
配置扫描Repositories所在的package及子package:
@EnableJpaRepositories(basePackages = "repository")
指定Repository类
@EnableJpaRepositories(basePackageClasses = BookRepository.class)
加载配置文件
Spring Boot 默认加载配置文件的位置是:
//后面会覆盖前面的
classpath:/,
classpath:/config/,
file:./,
file:./config/
Spring 定义的外部文件名称参数(优先级最高):
public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";
//设置为全局变量
System.setProperty("spring.config.additional-location", "file:${user.home}/.halo/,file:${user.home}/halo-dev/");
@ConfigurationProperties 把配置文件信息读取并自动封装成实体类
配置文件(Properties文件):
connection.username=admin
connection.password=aaa
connection.remoteAddress=192.168.1.1
@Data
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private String remoteAddress;
private String password ;
}
或者
@Configuration
public class Conf{
@Bean
@ConfigurationProperties(prefix = "connection")
public ConnectionSettings connectionSettings(){
return new ConnectionSettings();
}
}
使用
@Component
@EnableConfigurationProperties(Conf.class)
public class Test {
@Autowired
private Conf conf;
}
ObjectMapper 配置 SpringMVC 默认的解析工具 Jackson(json和java之间的相互转化)(配置类 @Configuration 中)
ObjectMapper:
package com.fasterxml.jackson.databind;
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
//如果是空对象的时候,不抛异常
builder.failOnEmptyBeans(false);
return builder.build();
}
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(Include.ALWAYS);
//反序列化的时候如果多了其他属性,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//如果是空对象的时候,不抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//属性值为null的不参与序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
RestTemplate REST服务API(配置类 @Configuration 中)
RESTful风格的Web服务架构,其目标是为了创建具有良好扩展性的分布式系统。
REST主要是用于定义接口名,接口名一般是用名词写,不用动词。
RestTemplate:
package org.springframework.web.client;
Spring 框架提供的 RestTemplate 类可用于在应用中调用 rest 服务。
它简化了与 http 服务的通信方式,统一了 RESTful 的标准,封装了 http 链接, 我们只需要传入 url 及返回值类型即可。
RestTemplate 默认依赖 JDK 提供 http 连接的能力(HttpURLConnection)。
如果有需要的话也可以通过 setRequestFactory() 方法替换。
@Bean
public RestTemplate httpsRestTemplate(RestTemplateBuilder builder) {
RestTemplate httpsRestTemplate = builder.build();
httpsRestTemplate.setRequestFactory(
new HttpComponentsClientHttpRequestFactory(HttpClientUtils.createHttpsClient(TIMEOUT)));
return httpsRestTemplate;
}
RestTemplate 包含以下几个部分:
HttpMessageConverter 对象转换器
ClientHttpRequestFactory 默认是JDK的HttpURLConnection
ResponseErrorHandler 异常处理
ClientHttpRequestInterceptor 请求拦截器
HttpClient
HttpClient:
package org.apache.http.client;
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性:
它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),
提高了开发的效率,也方便提高代码的健壮性。
/**
* Http client 工具类
*/
public class HttpClientUtils {
/** 默认超时时间:5s */
private final static int TIMEOUT = 5000;
private HttpClientUtils() {
}
/**
* 创建 https client
*/
@NonNull
public static CloseableHttpClient createHttpsClient(int timeout) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
//配置安全套接字SSL(获取不需要ssl认证的httpClient实例)
SSLContext sslContext = new SSLContextBuilder()
//解决https时的证书报错问题,信任所有证书
.loadTrustMaterial(null, (certificate, authType) -> true)
.build();
return HttpClients.custom()
.setSSLContext(sslContext)
//配置主机名验证(接受任何有效的SSL会话来匹配目标主机)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
//默认请求配置
.setDefaultRequestConfig(getReqeustConfig(timeout))
.build();
}
/**
* HttpClient内部三个超时时间的配置
*/
private static RequestConfig getReqeustConfig(int timeout) {
//用RequestConfig类的静态方法custom()获取RequestConfig.Builder配置器
return RequestConfig.custom()
.setConnectionRequestTimeout(timeout) //从连接池中获取连接的超时时间
.setConnectTimeout(timeout) //与服务器连接超时时间
.setSocketTimeout(timeout) //从服务器获取响应数据的超时时间
.build(); //调用配置器的build()方法返回RequestConfig对象。
}
}
RequestConfig HttpClient配置
RequestConfig:
package org.apache.http.client.config;
/**
* HttpClient内部三个超时时间的配置
*/
private static RequestConfig getReqeustConfig(int timeout) {
//用RequestConfig类的静态方法custom()获取 RequestConfig.Builder配置器
return RequestConfig.custom()
.setConnectionRequestTimeout(timeout) //从连接池中获取连接的超时时间
.setConnectTimeout(timeout) //与服务器连接超时时间
.setSocketTimeout(timeout) //从服务器获取响应数据的超时时间
.build(); //调用配置器的build()方法返回RequestConfig对象。
}
Halo(一)的更多相关文章
- Halo 的缔造者们在忙什么?
如果你自认为是一名主机游戏玩家,就一定知道 Halo.自 2001 年首代作品问世至今,十多年的磨炼已使得『光环』成为世界顶级的 FPS 游戏之一.<光环4>的推出,更让系列走向一个重要的 ...
- 超简单Centos+Docker+Halo搭建java向博客
首先,我就当你们了解docker基本知识了. 直接开始,全新的系统. 1. 安装Docker 移除旧的版本: $ sudo yum remove docker \ ...
- 关于halo博客系统的使用踩坑——忘记登录密码
踩坑: halo系统可以直接通过运行jar -jar halo-0.0.3.jar跑起来,也可以通过导入IDE然后运行Application的main方法跑起系统. h2数据库访问路径:http:// ...
- Halo(十三)
Spring Boot Actuator 请求跟踪 Spring Boot Actuator 的关键特性是在应用程序里提供众多 Web 接口, 通过它们了解应用程序运行时的内部状况,且能监控和度量 S ...
- Halo(八)
安全模块 用户描述类 /** * 基本 Entity */ @Data @MappedSuperclass public class BaseEntity { /** Create time */ @ ...
- Halo(七)
@ControllerAdvice 对Controller进行"切面"环绕 结合方法型注解 @ExceptionHandler 用于捕获Controller中抛出的指定类型的异常, ...
- Halo(六)
Spring publish-event 机制 监听者模式包含了一个监听者 Listener 与之对应的事件 Event,还有一个事件发布者 EventPublish. 过程就是 EventPubli ...
- Halo(五)
ApplicationPreparedEvent 监听事件 Event published once the application context has been refreshed but be ...
- Halo博客的搭建
今日主题:搭建一个私人博客 好多朋友和我说,能不能弄一个简单的私人博客啊,我说行吧,今天给你们一份福利啦! 搭建一个私人博客,就可以在自己的电脑上写博客了 Halo Halo 是一款现代化的个人独立博 ...
随机推荐
- Mac下通过npm安装webpack 、vuejs,以及引入jquery、bootstrap等(初稿)
前言: 初次接触前端开发技术,一些方向都是在同事的指引和自己的探索后,跑了个简易web,迈入全栈系列.由于是事后来的文章,故而暂只是杂记,写的粗略且不清晰,后续将补之. 主要参考文档: http:// ...
- httpClient连接工具类实测可用
package com.jeecms.common.util; import com.google.gson.Gson; import com.jeecms.cms.api.Constants; im ...
- MySQL索引优化之双表示例
select * from tableA a left join tableB b on a.f_id = b.id; 索引建tableB表上面, 因为left join 注定左表全都有,所以应该关心 ...
- 对于vue绑定的model值里边get和set的小动作
先看下例子: template里边内容: <el-form-item label="导航条类型"> <el-radio-group v-model="n ...
- C#链接mysql出现 One of the identified items was in an invalid format
这个问题在tolist查询结果的时候就会出现但是count就不会出现,后来才发现是数据生成工具生成出来的ID有问题导致的,只要保证iD不重复并且按照指定的类型建立ID就可以了
- 控件识别工具Inspect.exe下载
一.Inspect.exe 控件识别工具.官网上说通过下载安装Windows SDK后,可以在目录C:\Program Files (x86)\Microsoft SDKs\Windows Kits\ ...
- spring boot 尚桂谷学习笔记08 Docker ---Web
------Docker------ 简介:Docker是一个开元的应用容器引擎,性能非常高 已经安装好的软件打包成一个镜像放到服务器中运行镜像 MySQL容器,Redis容器...... Docke ...
- LeetCode:旋转数组
最近看了一道题,自己做个过后又参考了网上的解法,为了加深对这个解法的理解和记忆于是有了这篇博客,供自己以后复习用 题目: 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数. 示例 ...
- Numpy基础之创建与属性
import numpy as np ''' 1.数组的创建:np.array([]) 2.数组对象的类型:type() 3.数据类型:a.dtype 4.数组的型shape:(4,2,3) 5.定义 ...
- 53-python基础-python3-列表-列表解析
列表解析 将for循环和创建新元素的代码合并成一行,并自动附加新元素. 实例:使用列表解析创建平方数列表. 首先指定一个描述性的列表名,如squares : 然后,指定一个左方括号,并定义一个表达式, ...