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 是一款现代化的个人独立博 ...
随机推荐
- Oracle11g新建用户及用户表空间
/* 建立数据表空间 */CREATE TABLESPACE SP_TAB DATAFILE '/u01/app/oracle/oradata/orcl/tab1_1.dbf' size 1024M ...
- centos7安装完成之后必要的配置
一配置yum源 curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo wget ...
- shell脚本学习 (10) 从结构化文本提取数据
1提取/ 后的数据 sed -e 's=/.*==' do.txt 2 sed -e 's=/.*=='\ -e 's=^\([^:]*\):\(.*\) \([^ ]*\)=\1:\3, \2=' ...
- BUUCTF | 高明的黑客
这一题一开始我没有理解"www.tar.gz"的涵义,还以为有一个其他的网站叫这个,后来才突然顿悟他也有可能是一个目录!!!地址栏输入”/www.tar.gz“ 然后就可以得到源码 ...
- PPT技巧
1.秋叶个人的PPT三分钟教程 http://www.pptfans.cn/315656.html 2.<说服力-让你的PPT会说话>秋叶 3.<三体> https://w ...
- 踩坑记之字体图标在webpack中
首先介绍一个还不错的字体图标库: font-awesome 是在发现bootstrap在npm下载后没有font包以后重新找的字体库,内容还挺丰富的,好像还有动态图,感兴趣的可以看一下 我的环境是we ...
- composer 国内加速,修改镜像源
为什么慢 由于默认情况下执行 composer 各种命令是去国外的 composer 官方镜像源获取需要安装的具体软件信息,所以在不使用代理.不翻墙的情况下,从国内访问国外服务器的速度相对比较慢 如何 ...
- centos7运行yum报如下提示:Run "yum repolist all" to see the repos you have
centos7运行yum报如下提示: There are no enabled repos. Run "yum repolist all" to see the repos you ...
- 关于toString()的一些事情
Java上输出一个数组的时候,不可以直接输出 System.out.println(arr); 直接输出数据的名称会输出数组的内存地址.换句话说,他的输出是: getClass().getName() ...
- Spring 常犯的十大错误,打死都不要犯!
原文:https://www.toptal.com/spring/top-10-most-common-spring-framework-mistakes 作者:Toni Kukurin,译者:万想 ...