├── springboot-tutorials
├── logs
│ └── app.log
├── src
│ ├── main
│ │ ├── resources
│ │ │ ├── templates
│ │ │ │ ├── footer.ftl
│ │ │ │ ├── macro.ftl
│ │ │ │ └── list.ftl
│ │ │ ├── META-INF
│ │ │ │ └── spring-devtools.properties
│ │ │ ├── ehcache.xml
│ │ │ ├── config
│ │ │ │ └── logback-spring.xml
│ │ │ ├── mybatis-config.xml
│ │ │ ├── application.yml
│ │ │ └── mappers
│ │ │ │ └── UserMapper.xml
│ │ └── java
│ │ │ └── vip
│ │ │ └── codehome
│ │ │ └── springboot
│ │ │ └── tutorials
│ │ │ ├── anno
│ │ │ ├── TestService.java
│ │ │ ├── ImportTestService.java
│ │ │ ├── ImportTestServiceSelector.java
│ │ │ └── ImportTestServiceBeanDefinitionRegistrar.java
│ │ │ ├── mapper
│ │ │ ├── TkUserMapper.java
│ │ │ └── UserMapper.java
│ │ │ ├── vo
│ │ │ └── UserInfoVO.java
│ │ │ ├── es
│ │ │ ├── LogRepository.java
│ │ │ └── LogDO.java
│ │ │ ├── config
│ │ │ ├── UserProperties.java
│ │ │ ├── Jsr303Config.java
│ │ │ ├── WebsocketConfig.java
│ │ │ ├── ExceptionResolver.java
│ │ │ ├── SwaggerConfig.java
│ │ │ ├── AsyncConfig.java
│ │ │ ├── CustomRedisCacheManager.java
│ │ │ └── RedisConfig.java
│ │ │ ├── dto
│ │ │ └── LoginDTO.java
│ │ │ ├── healthIndicator
│ │ │ ├── CustomHealthIndicator.java
│ │ │ ├── JmxDemoMBean.java
│ │ │ └── MyEndpoint.java
│ │ │ ├── common
│ │ │ ├── ApiCommonCodeEnum.java
│ │ │ ├── R.java
│ │ │ └── BusinessException.java
│ │ │ ├── controller
│ │ │ ├── FileUploadController.java
│ │ │ ├── ContentController.java
│ │ │ ├── Jsr303Controller.java
│ │ │ ├── RequestMappingController.java
│ │ │ ├── PropController.java
│ │ │ ├── UserController.java
│ │ │ ├── MvcController.java
│ │ │ └── SwaggerUserController.java
│ │ │ ├── service
│ │ │ ├── UserService.java
│ │ │ └── impl
│ │ │ │ └── UserServiceImpl.java
│ │ │ ├── dao
│ │ │ └── UserRepository.java
│ │ │ ├── filter
│ │ │ ├── LogFilter.java
│ │ │ ├── LogFilterConfiguration.java
│ │ │ └── AuthFilter.java
│ │ │ ├── handler
│ │ │ ├── HandlerConfig.java
│ │ │ └── LogHandler.java
│ │ │ ├── entity
│ │ │ └── UserDO.java
│ │ │ ├── util
│ │ │ ├── FreemarkerUtil.java
│ │ │ ├── JsonUtil.java
│ │ │ └── ExUtil.java
│ │ │ ├── asynctask
│ │ │ └── UserServiceSyncTask.java
│ │ │ ├── asyncrequest
│ │ │ ├── ConfigController.java
│ │ │ └── AsyncRequsetDemoController.java
│ │ │ ├── scheduled
│ │ │ ├── ScheduledTaskConfig.java
│ │ │ └── ScheduledTask.java
│ │ │ ├── SpringbootTutorialsApplication.java
│ │ │ ├── transaction
│ │ │ ├── UserServiceTranasction.java
│ │ │ └── TxAdviceInterceptor.java
│ │ │ └── batch
│ │ │ └── BatchJobConfig.java
│ └── test
│ │ └── java
│ │ └── vip
│ │ └── codehome
│ │ └── springboot
│ │ └── tutorials
│ │ ├── service
│ │ └── UserServiceCacheTest.java
│ │ ├── SpringbootTutorialsApplicationTests.java
│ │ ├── transaction
│ │ └── TransactionTest.java
│ │ ├── dao
│ │ ├── UserRepositoryTest.java
│ │ ├── TkUserMapperTest.java
│ │ └── UserMapperTest.java
│ │ ├── es
│ │ └── ESLogCURDTest.java
│ │ └── controller
│ │ └── UserControllerTest.java
├── .gitignore
├── pom.xml
└── intellij-java-google-style.xml
├── jsr303.png
├── README.md
└── LICENSE
/springboot-tutorials/logs/app.log:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/templates/footer.ftl:
--------------------------------------------------------------------------------
1 | @copyright ${copyright}
--------------------------------------------------------------------------------
/jsr303.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mytianya/springboot-tutorials/HEAD/jsr303.png
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/templates/macro.ftl:
--------------------------------------------------------------------------------
1 | <#macro layout title,keywords>
2 |
${title}
3 |
4 | #macro>
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/META-INF/ spring-devtools.properties:
--------------------------------------------------------------------------------
1 | restart.include.mapper=/mapper-[\\w-\\.]+jar
2 | restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/anno/TestService.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.anno;
2 |
3 | /***
4 | *@author zyw
5 | *@createTime 2020/8/15 10:04
6 | *@description
7 | *@version 1.0
8 | */
9 | public class TestService {
10 | }
11 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/mapper/TkUserMapper.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.mapper;
2 |
3 | import tk.mybatis.mapper.common.Mapper;
4 | import tk.mybatis.mapper.common.MySqlMapper;
5 | import vip.codehome.springboot.tutorials.entity.UserDO;
6 |
7 | public interface TkUserMapper extends Mapper, MySqlMapper {
8 | }
9 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/vo/UserInfoVO.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.vo;
2 |
3 | import io.swagger.annotations.ApiModel;
4 | import io.swagger.annotations.ApiModelProperty;
5 | import lombok.Data;
6 |
7 | @Data
8 | @ApiModel
9 | public class UserInfoVO {
10 | @ApiModelProperty(value = "用户昵称")
11 | String nickname;
12 | @ApiModelProperty(value = "登录后生产的token")
13 | String token;
14 | }
15 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/es/LogRepository.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.es;
2 |
3 | import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
4 | import org.springframework.stereotype.Repository;
5 |
6 | /**
7 | * @author dsyslove@163.com
8 | * @createtime 2021/2/2--14:25
9 | * @description
10 | **/
11 | //@Repository
12 | public interface LogRepository {//extends ElasticsearchRepository {
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/UserProperties.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import lombok.Data;
4 | import org.springframework.boot.context.properties.ConfigurationProperties;
5 | import org.springframework.context.annotation.Configuration;
6 |
7 | import java.io.Serializable;
8 |
9 | @Configuration
10 | @ConfigurationProperties(prefix = "user")
11 | @Data
12 | public class UserProperties {
13 | String userName;
14 | int age;
15 | boolean forbidden;
16 | }
17 |
--------------------------------------------------------------------------------
/springboot-tutorials/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/anno/ImportTestService.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.anno;
2 |
3 | import org.springframework.context.annotation.Import;
4 |
5 | /***
6 | *@author zyw
7 | *@createTime 2020/8/15 10:01
8 | *@description
9 | *@version 1.0
10 | * 1.在类上使用,写类的全路径导入IOC容器
11 | */
12 | //@Import({vip.codehome.springboot.tutorials.anno.ImportDemoService.class})
13 | //@Import({ImportTestServiceSelector.class})
14 | @Import({ImportTestServiceBeanDefinitionRegistrar.class})
15 | public class ImportTestService {
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/ehcache.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/anno/ImportTestServiceSelector.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.anno;
2 |
3 | import org.springframework.context.annotation.ImportSelector;
4 | import org.springframework.core.type.AnnotationMetadata;
5 |
6 | /***
7 | *@author zyw
8 | *@createTime 2020/8/15 10:03
9 | *@description
10 | *@version 1.0
11 | */
12 | public class ImportTestServiceSelector implements ImportSelector {
13 | @Override
14 | public String[] selectImports(AnnotationMetadata annotationMetadata) {
15 | return new String[]{"vip.codehome.springboot.tutorials.anno.ImportDemoService"};
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/service/UserServiceCacheTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.service;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.boot.test.context.SpringBootTest;
7 | import org.springframework.test.context.junit4.SpringRunner;
8 |
9 | /***
10 | *@author zyw
11 | *@createTime 2020/8/27 10:15
12 | *@description
13 | *@version 1.0
14 | */
15 | @RunWith(SpringRunner.class)
16 | @SpringBootTest
17 | public class UserServiceCacheTest {
18 | @Autowired
19 | UserService userService;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.mapper;
2 |
3 | import org.apache.ibatis.annotations.Mapper;
4 | import org.springframework.stereotype.Repository;
5 | import vip.codehome.springboot.tutorials.entity.UserDO;
6 |
7 | import java.util.List;
8 |
9 | @Mapper
10 | @Repository
11 | public interface UserMapper {
12 | int insert(UserDO userDO);
13 | List select(UserDO userDO);
14 | int update(UserDO userDO);
15 | int delete(UserDO userDO);
16 | int insertBatch(List list);
17 | int updateBatch(List list);
18 | int deleteBatch(Long[] array);
19 | }
20 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/dto/LoginDTO.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.dto;
2 |
3 | import io.swagger.annotations.ApiModel;
4 | import io.swagger.annotations.ApiModelProperty;
5 | import lombok.Data;
6 |
7 | import javax.validation.constraints.NotBlank;
8 | import javax.validation.constraints.Size;
9 |
10 | @Data
11 | @ApiModel
12 | public class LoginDTO {
13 | @ApiModelProperty(value = "用户账号或者邮箱")
14 | @Size(min = 8,message = "账号长度大于8")
15 | String account;
16 | @ApiModelProperty(value = "用户密码")
17 | @NotBlank(message = "密码不能为空")
18 | String passwd;
19 | @ApiModelProperty(value = "用户密码")
20 | String verifyCode;
21 | }
22 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/healthIndicator/CustomHealthIndicator.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.healthIndicator;
2 |
3 | import org.springframework.boot.actuate.health.AbstractHealthIndicator;
4 | import org.springframework.boot.actuate.health.Health;
5 | import org.springframework.stereotype.Component;
6 |
7 | /***
8 | * @author 道士吟诗
9 | * @date 2021/5/5-下午10:52
10 | * @description
11 | ***/
12 | @Component
13 | public class CustomHealthIndicator extends AbstractHealthIndicator {
14 | @Override
15 | protected void doHealthCheck(Health.Builder builder) throws Exception {
16 | builder.up().withDetail("app","Alive");
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/common/ApiCommonCodeEnum.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.common;
2 |
3 | public enum ApiCommonCodeEnum {
4 | FAIL(1,"调用出错"),
5 | OK(0,"调用成功");
6 | int code;
7 | String msg;
8 | ApiCommonCodeEnum(int code,String msg){
9 | this.code=code;
10 | this.msg=msg;
11 | }
12 |
13 | public int getCode() {
14 | return code;
15 | }
16 |
17 | private void setCode(int code) {
18 | this.code = code;
19 | }
20 |
21 | public String getMsg() {
22 | return msg;
23 | }
24 |
25 | private void setMsg(String msg) {
26 | this.msg = msg;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/FileUploadController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import org.springframework.http.ResponseEntity;
4 | import org.springframework.web.bind.annotation.PostMapping;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 | import org.springframework.web.multipart.MultipartFile;
8 |
9 | /**
10 | * @author dsys
11 | * @version v1.0
12 | * max-file-size设置能接受文件的最大带下
13 | * max-request-size 1次能接受文件的大小
14 | * 分片上传、断点续传、秒传、文件夹上传
15 | **/
16 | @RestController
17 | @RequestMapping("/file")
18 | public class FileUploadController {
19 | @PostMapping("/upload")
20 | public ResponseEntity upload(MultipartFile file){
21 | return ResponseEntity.ok().build();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/service/UserService.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.service;
2 |
3 | import org.springframework.cache.annotation.CacheEvict;
4 | import org.springframework.cache.annotation.CachePut;
5 | import org.springframework.cache.annotation.Cacheable;
6 | import vip.codehome.springboot.tutorials.entity.UserDO;
7 |
8 | import java.util.List;
9 |
10 | /***
11 | *@author zyw
12 | *@createTime 2020/8/27 10:12
13 | *@description
14 | *@version 1.0
15 | */
16 | public interface UserService {
17 | @Cacheable(value = "users",key = "#userDO.id")
18 | List queryUsers(UserDO userDO);
19 | @CachePut(value = "users",key ="#userDO.id" )
20 | void saveUser(UserDO userDO);
21 | @CacheEvict(value = "users",key = "#userDO.id")
22 | void removeUser(UserDO userDO);
23 | }
24 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/ContentController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.ui.Model;
5 | import org.springframework.web.bind.annotation.PathVariable;
6 | import org.springframework.web.bind.annotation.RequestMapping;
7 | import vip.codehome.springboot.tutorials.entity.UserDO;
8 |
9 | import java.util.Arrays;
10 |
11 | @Controller
12 | public class ContentController {
13 |
14 | @RequestMapping("/freemark/{demo}")
15 | public String demo(@PathVariable("demo") String demo, Model model) {
16 | model.addAttribute("userList", Arrays.asList(new UserDO()));
17 | model.addAttribute("flag", false);
18 | model.addAttribute("copyright", "编程之家:www.codehome.vip");
19 | return demo;
20 | }
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/healthIndicator/JmxDemoMBean.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.healthIndicator;
2 |
3 | import org.springframework.jmx.export.annotation.ManagedAttribute;
4 | import org.springframework.jmx.export.annotation.ManagedOperation;
5 | import org.springframework.jmx.export.annotation.ManagedResource;
6 | import org.springframework.stereotype.Component;
7 |
8 | /***
9 | * @author 道士吟诗
10 | * @date 2021/5/7-下午10:36
11 | * @description
12 | ***/
13 | @Component
14 | @ManagedResource(objectName = "vip.codehome:name=jxmdemo",description = "jmx test")
15 | public class JmxDemoMBean {
16 | private long version=1;
17 | @ManagedAttribute
18 | public long getVersion(){
19 | return version;
20 | }
21 | @ManagedOperation
22 | public void change(int version){
23 | this.version=version;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/templates/list.ftl:
--------------------------------------------------------------------------------
1 |
2 |
3 | 测试freemarker
4 | list循环
5 | <#list userList as user>
6 | ${user.loginTime}
7 | #list>
8 | <#list userList>
9 |
10 | <#items as user>
11 | ${user.loginTime}<#sep>
12 | #items>
13 |
14 | #list>
15 |
16 | <#if flag>
17 | flag is true
18 | <#else>
19 | flag is false
20 | #if>
21 |
22 | include使用
23 | <#include "footer.ftl"/>
24 |
25 | 内置函数使用
26 | ${userList?size}
27 | 自定义指令
28 | <#macro test user remark>
29 | ${user.loginTime} ${remark}
30 | <#nested>
31 | #macro>
32 | <@test user=userList[0] remark="测试">插槽@test>
33 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/Jsr303Config.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import org.hibernate.validator.HibernateValidator;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 |
7 | import javax.validation.Validation;
8 | import javax.validation.Validator;
9 | import javax.validation.ValidatorFactory;
10 |
11 | /**
12 | * 配置Jsr303 hibernate validator快速失败模式
13 | */
14 | @Configuration
15 | public class Jsr303Config {
16 | @Bean
17 | public Validator validator(){
18 | ValidatorFactory validatorFactory = Validation
19 | .byProvider( HibernateValidator.class )
20 | .configure()
21 | .failFast( true )
22 | .buildValidatorFactory();
23 | return validatorFactory.getValidator();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/WebsocketConfig.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 |
5 | import javax.websocket.OnOpen;
6 | import javax.websocket.Session;
7 | import javax.websocket.server.ServerEndpoint;
8 | import java.util.Map;
9 | import java.util.concurrent.ConcurrentHashMap;
10 |
11 | /**
12 | * @author:
13 | * @description:
14 | * @creatTime: 2020/9/4--22:08
15 | */
16 | @ServerEndpoint("/server")
17 | @Slf4j
18 | public class WebsocketConfig {
19 | private static final Map clients=new ConcurrentHashMap<>();
20 | @OnOpen
21 | public void connect(Session session){
22 | String userId=session.getQueryString();
23 | try{
24 | clients.remove(userId);
25 | }catch (Exception e){
26 | log.error(e.getMessage());
27 | }
28 | clients.put(userId,session);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/dao/UserRepository.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.dao;
2 |
3 | import org.springframework.data.domain.Page;
4 | import org.springframework.data.domain.Pageable;
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 | import org.springframework.data.jpa.repository.Query;
7 | import org.springframework.data.repository.query.Param;
8 | import org.springframework.stereotype.Repository;
9 | import vip.codehome.springboot.tutorials.entity.UserDO;
10 |
11 | import java.util.List;
12 |
13 |
14 | @Repository
15 | public interface UserRepository extends JpaRepository {
16 | @Query("from tb_user u where u.name like :name")
17 | Page findUserDOByUserName(@Param("name")String name, Pageable pageable);
18 | Page findAll(Pageable pageable);
19 | List findUserDOByAccountAndAgeAndNameLike(String account,int age,String userName);
20 | }
21 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/common/R.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.common;
2 |
3 | import lombok.Data;
4 |
5 | @Data
6 | public class R {
7 | private int code;
8 | private T data;
9 | private String msg;
10 | public R() {
11 | }
12 | public static R ok(T data) {
13 | return fill(data,ApiCommonCodeEnum.OK);
14 | }
15 |
16 | public static R failed(String msg) {
17 | return fill( null, ApiCommonCodeEnum.FAIL);
18 | }
19 | public static R failed(ApiCommonCodeEnum apiEnum) {
20 | return fill( null, apiEnum);
21 | }
22 | public static R fill(T data, ApiCommonCodeEnum apiEnum) {
23 | return fill(apiEnum.getCode(),data,apiEnum.getMsg());
24 | }
25 | public static R fill(int code,T data,String msg) {
26 | R R = new R();
27 | R.setCode(code);
28 | R.setData(data);
29 | R.setMsg(msg);
30 | return R;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/filter/LogFilter.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.filter;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 |
5 | import javax.servlet.*;
6 | import javax.servlet.http.HttpServletRequest;
7 | import java.io.IOException;
8 |
9 | /***
10 | *@author zyw
11 | *@createTime 2020/8/17 10:31
12 | *@description
13 | *@version 1.0
14 | */
15 | @Slf4j
16 | public class LogFilter implements Filter {
17 | @Override
18 | public void init(FilterConfig filterConfig) throws ServletException {
19 |
20 | }
21 |
22 | @Override
23 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
24 | HttpServletRequest req=(HttpServletRequest)servletRequest;
25 | log.info(req.getRequestURI());
26 | filterChain.doFilter(servletRequest,servletResponse);
27 | }
28 |
29 | @Override
30 | public void destroy() {
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/handler/HandlerConfig.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.handler;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
6 |
7 | /***
8 | *@author zyw
9 | *@createTime 2020/8/17 11:32
10 | *@description
11 | *@version 1.0
12 | * 1. Filter是servlet规范,使用范围是web程序,拦截器不限于web程序,也可以用于Application、Swing程序中
13 | * 2. Filter是servlet规范中定义,是servlet容器支持的。拦截器是Spring容器内,是spring框架支持的
14 | * 3. 拦截器是Spring的一个组件,额能够使用spring中对象,如Service对象、数据源、事务管理、通过IOC注入容器即可,filter则不能
15 | * 4. filter在servlet前后起作用,拦截器能够深入方法的前后,异常抛出前后。
16 | * 5. 所以在springboot项目中一般优先使用拦截器
17 | */
18 | @Configuration
19 | public class HandlerConfig implements WebMvcConfigurer {
20 | @Override
21 | public void addInterceptors(InterceptorRegistry registry) {
22 | registry.addInterceptor(new LogHandler());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/filter/LogFilterConfiguration.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.filter;
2 |
3 | import org.springframework.boot.web.servlet.FilterRegistrationBean;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 |
7 | /***
8 | *@author zyw
9 | *@createTime 2020/8/17 10:33
10 | *@description
11 | *@version 1.0
12 | */
13 | @Configuration
14 | public class LogFilterConfiguration {
15 | @Bean
16 | public FilterRegistrationBean registrationBean(){
17 | FilterRegistrationBean registrationBean=new FilterRegistrationBean();
18 | registrationBean.setFilter(new LogFilter());
19 | //匹配的过滤器
20 | registrationBean.addUrlPatterns("/*");
21 | //过滤器名称
22 | registrationBean.setName("logFilter");
23 | registrationBean.setAsyncSupported(true);
24 | //过滤器顺序
25 | registrationBean.setOrder(1);
26 | return registrationBean;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/entity/UserDO.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.entity;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import javax.persistence.*;
8 | import javax.xml.bind.annotation.XmlRootElement;
9 | import java.io.Serializable;
10 | import java.time.LocalDateTime;
11 | import java.util.Date;
12 |
13 | @Entity(name = "tb_user")
14 | @Data
15 | @NoArgsConstructor
16 | @AllArgsConstructor
17 | @XmlRootElement(name = "User")
18 | @Table(name = "tb_user")
19 | public class UserDO implements Serializable {
20 | @Id
21 | @GeneratedValue(strategy = GenerationType.IDENTITY)
22 | private Long id;
23 | @Column(name = "name",nullable = false)
24 | String name;
25 | String account;
26 | String passwd;
27 | Integer age=0;
28 | Boolean forbidden=true;
29 | // @Temporal(value = TemporalType.TIMESTAMP)
30 | LocalDateTime loginTime=LocalDateTime.now();
31 | @Transient
32 | String token;
33 | }
34 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/SpringbootTutorialsApplicationTests.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.data.domain.Page;
7 | import org.springframework.data.domain.PageRequest;
8 | import org.springframework.data.domain.Pageable;
9 | import vip.codehome.springboot.tutorials.dao.UserRepository;
10 | import vip.codehome.springboot.tutorials.entity.UserDO;
11 |
12 | import java.util.List;
13 |
14 |
15 | @SpringBootTest
16 | class SpringbootTutorialsApplicationTests {
17 | @Autowired
18 | UserRepository userRepository;
19 | @Test
20 | void contextLoads() {
21 | Pageable pageable= PageRequest.of(0,10);
22 | Page pageUsers=userRepository.findAll(pageable
23 | );
24 | List users=pageUsers.getContent();
25 | int totalPages= pageUsers.getTotalPages();
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/transaction/TransactionTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.transaction;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 | import org.junit.runner.RunWith;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.test.context.junit4.SpringRunner;
9 |
10 | import java.util.UUID;
11 |
12 | @SpringBootTest
13 | @RunWith(SpringRunner.class)
14 | public class TransactionTest {
15 | @Autowired
16 | UserServiceTranasction userServiceTranasction;
17 | @Test
18 | public void testInsert(){
19 | Assert.assertEquals((long)userServiceTranasction.save(100,"codehome"),1);
20 | }
21 | @Test
22 | public void testInsert1(){
23 | Assert.assertEquals((long)userServiceTranasction.save1(100,"codehome"),1);
24 | }
25 | @Test
26 | public void testInsert2(){
27 | Assert.assertEquals((long)userServiceTranasction.save2(1000,"codehome"),1);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/anno/ImportTestServiceBeanDefinitionRegistrar.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.anno;
2 |
3 | import org.springframework.beans.factory.support.BeanDefinitionRegistry;
4 | import org.springframework.beans.factory.support.BeanNameGenerator;
5 | import org.springframework.beans.factory.support.RootBeanDefinition;
6 | import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
7 | import org.springframework.core.type.AnnotationMetadata;
8 |
9 | /***
10 | *@author zyw
11 | *@createTime 2020/8/15 10:07
12 | *@description
13 | *@version 1.0
14 | */
15 |
16 | public class ImportTestServiceBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
17 |
18 | @Override
19 | public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
20 | RootBeanDefinition testServiceBeanDefinition=new RootBeanDefinition(TestService.class);
21 | registry.registerBeanDefinition("testService",testServiceBeanDefinition);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/es/LogDO.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.es;
2 |
3 | import java.util.Date;
4 | import lombok.Data;
5 | import org.springframework.data.annotation.Id;
6 | import org.springframework.data.elasticsearch.annotations.Document;
7 | import org.springframework.data.elasticsearch.annotations.Field;
8 | import org.springframework.data.elasticsearch.annotations.FieldType;
9 |
10 | /**
11 | * @author dsyslove@163.com
12 | * @createtime 2021/2/2--14:06
13 | * @description
14 | **/
15 | @Data
16 | @Document(indexName = "msglog")
17 | public class LogDO {
18 | @Id
19 | private String id;
20 | private String msgSeqn;
21 | private String msgReqn;
22 | private String msgRaw;
23 | private String msgStatus;
24 | private String msgFrom;
25 | private String msgTo;
26 | private String msgStyp;
27 | private Date logTime;
28 | private String logSystem;
29 | private String logModule;
30 | private String remark;
31 | private String msgSndr;
32 | private String msgRcvr;
33 | private Date msgDdtm;
34 | }
35 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/util/FreemarkerUtil.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.util;
2 |
3 |
4 | import freemarker.template.Template;
5 | import java.util.Map;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 | import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
9 | import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
10 |
11 | /**
12 | * @author zyw
13 | * @mail dsyslove@163.com
14 | * @createtime 2021/5/19--15:26
15 | * @description
16 | **/
17 | @Service
18 | public class FreemarkerUtil {
19 | @Autowired
20 | private FreeMarkerConfigurer freeMarkerConfigurer;
21 | public String parse(String templateName, Map params){
22 | try {
23 | Template template= freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
24 | String text=FreeMarkerTemplateUtils.processTemplateIntoString(template,params);
25 | return text;
26 | } catch (Exception e) {
27 | return "";
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/service/impl/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.service.impl;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.stereotype.Service;
5 | import vip.codehome.springboot.tutorials.entity.UserDO;
6 | import vip.codehome.springboot.tutorials.mapper.UserMapper;
7 | import vip.codehome.springboot.tutorials.service.UserService;
8 |
9 | import java.util.List;
10 |
11 | /***
12 | *@author zyw
13 | *@createTime 2020/8/27 10:12
14 | *@description
15 | *@version 1.0
16 | */
17 | //@Service
18 | public class UserServiceImpl implements UserService {
19 | @Autowired
20 | UserMapper userMapper;
21 |
22 | @Override
23 | public List queryUsers(UserDO userDO) {
24 | return userMapper.select(userDO);
25 | }
26 |
27 | @Override
28 | public void saveUser(UserDO userDO) {
29 | userMapper.insert(userDO);
30 | }
31 |
32 | @Override
33 | public void removeUser(UserDO userDO) {
34 | userMapper.delete(userDO);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/asynctask/UserServiceSyncTask.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.asynctask;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import org.springframework.scheduling.annotation.Async;
5 | import org.springframework.scheduling.annotation.AsyncResult;
6 | import org.springframework.stereotype.Component;
7 |
8 | import java.util.concurrent.Future;
9 | import java.util.concurrent.TimeUnit;
10 |
11 | @Component
12 | @Slf4j
13 | public class UserServiceSyncTask {
14 | @Async
15 | public void sendEmail(){
16 | try {
17 | TimeUnit.SECONDS.sleep(1);
18 | } catch (InterruptedException e) {
19 | e.printStackTrace();
20 | }
21 | log.info(Thread.currentThread().getName());
22 | }
23 | @Async
24 | public Future echo(String msg){
25 | try {
26 | Thread.sleep(5000);
27 | return new AsyncResult(Thread.currentThread().getName()+"hello world !!!!");
28 | } catch (InterruptedException e) {
29 | //
30 | }
31 | return null;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/Jsr303Controller.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import org.springframework.validation.BindingResult;
4 | import org.springframework.validation.ObjectError;
5 | import org.springframework.web.bind.annotation.PostMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 | import vip.codehome.springboot.tutorials.dto.LoginDTO;
8 | import vip.codehome.springboot.tutorials.util.ExUtil;
9 |
10 | import javax.validation.Valid;
11 |
12 | @RestController
13 | public class Jsr303Controller {
14 | @PostMapping("/logon")
15 | public String logon(@Valid LoginDTO loginDTO, BindingResult result){
16 | check(result);
17 | return "ok";
18 | }
19 | public static void check(BindingResult result){
20 | StringBuffer sb=new StringBuffer();
21 | if(result.hasErrors()){
22 | for (ObjectError error : result.getAllErrors()) {
23 | sb.append(error.getDefaultMessage());
24 | }
25 | ExUtil.throwBusException(sb.toString());
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/asyncrequest/ConfigController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.asyncrequest;
2 |
3 | import org.springframework.web.bind.annotation.GetMapping;
4 | import org.springframework.web.bind.annotation.PostMapping;
5 | import org.springframework.web.bind.annotation.RestController;
6 | import org.springframework.web.context.request.async.DeferredResult;
7 |
8 | import java.util.HashSet;
9 | import java.util.Set;
10 |
11 | /***
12 | * @author 道士吟诗
13 | * @date 2021/5/18-下午11:08
14 | * @description
15 | ***/
16 | @RestController
17 | public class ConfigController {
18 | public Set> deferredResultSet=new HashSet<>();
19 | @GetMapping("/fetch")
20 | public DeferredResult fetch(){
21 | DeferredResult deferredResult=new DeferredResult<>();
22 | deferredResultSet.add(deferredResult);
23 | return deferredResult;
24 | }
25 | @PostMapping("/update")
26 | public void update(){
27 | for(DeferredResult deferredResult:deferredResultSet){
28 | deferredResult.setResult("ok");
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/filter/AuthFilter.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.filter;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 |
5 | import javax.servlet.*;
6 | import javax.servlet.annotation.WebFilter;
7 | import java.io.IOException;
8 |
9 | /***
10 | *@author zyw
11 | *@createTime 2020/8/17 10:37
12 | *@description
13 | *@version 1.0
14 | * WebFilter这个注解并没有指定执行顺序的属性,其执行顺序依赖于Filter的名称
15 | * 是根据Filter类名(注意不是配置的filter的名字)的字母顺序倒序排列
16 | * ,并且@WebFilter指定的过滤器优先级都高于FilterRegistrationBean配置的过滤器。
17 | */
18 | @WebFilter(urlPatterns = "/*",filterName = "authFiler",asyncSupported = true)
19 | @Slf4j
20 | public class AuthFilter implements Filter {
21 | @Override
22 | public void init(FilterConfig filterConfig) throws ServletException {
23 |
24 | }
25 |
26 | @Override
27 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
28 | log.info("进行权限校验.........");
29 | chain.doFilter(servletRequest,servletResponse);
30 | }
31 |
32 | @Override
33 | public void destroy() {
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/dao/UserRepositoryTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.dao;
2 |
3 | import org.junit.Assert;
4 | import org.junit.Ignore;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.data.domain.Page;
10 | import org.springframework.data.domain.PageRequest;
11 | import org.springframework.data.domain.Pageable;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 | import vip.codehome.springboot.tutorials.entity.UserDO;
14 |
15 | @RunWith(SpringRunner.class)
16 | @SpringBootTest
17 | public class UserRepositoryTest {
18 | @Autowired
19 | UserRepository userRepository;
20 | @Test
21 | @Ignore
22 | public void testFindAll(){
23 | Page userDOS= userRepository.findAll(PageRequest.of(1,10));
24 | Assert.assertNotNull(userDOS.getContent());
25 | }
26 | @Test(expected = RuntimeException.class)
27 | public void testNullPointerException(){
28 | throw new RuntimeException();
29 | }
30 | }
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/RequestMappingController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | import javax.servlet.http.HttpServletRequest;
9 |
10 | @RestController
11 | public class RequestMappingController {
12 | @GetMapping
13 | public String handleAll(HttpServletRequest req){
14 | return "getMapping为空匹配:"+req.getRequestURI();
15 | }
16 | @GetMapping("/")
17 | public String handleXie(HttpServletRequest req){
18 | return "getMapping /匹配:"+req.getRequestURI();
19 | }
20 | @GetMapping("/**")
21 | public String handleStarStar(HttpServletRequest req){
22 | return "getMapping /**匹配:"+req.getRequestURI();
23 | }
24 | @RequestMapping("{prefix}")
25 | public String handlePathV(HttpServletRequest req){
26 | return "{prefix}match:"+req.getRequestURI();
27 | }
28 | @RequestMapping("{prefix}/{slug}")
29 | public String handlePathVV(HttpServletRequest req){
30 | return "{prefix}match:"+req.getRequestURI();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/scheduled/ScheduledTaskConfig.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.scheduled;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.core.task.TaskExecutor;
6 | import org.springframework.scheduling.annotation.EnableScheduling;
7 | import org.springframework.scheduling.annotation.SchedulingConfigurer;
8 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
9 | import org.springframework.scheduling.config.ScheduledTaskRegistrar;
10 | //@EnableScheduling
11 | @Configuration
12 | public class ScheduledTaskConfig implements SchedulingConfigurer {
13 | @Override
14 | public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
15 | scheduledTaskRegistrar.setScheduler(taskExecutor());
16 | }
17 |
18 | public ThreadPoolTaskScheduler taskExecutor() {
19 | ThreadPoolTaskScheduler scheduler=new ThreadPoolTaskScheduler();
20 | // 设置核心线程数
21 | scheduler.setPoolSize(8);
22 | // 设置默认线程名称
23 | scheduler.setThreadNamePrefix("CodehomeScheduledTask-");
24 | scheduler.setWaitForTasksToCompleteOnShutdown(true);
25 | scheduler.initialize();
26 | return scheduler;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/SpringbootTutorialsApplication.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials;
2 |
3 | import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.boot.web.servlet.ServletComponentScan;
7 | import org.springframework.cache.annotation.EnableCaching;
8 | import org.springframework.context.annotation.ComponentScan;
9 | import org.springframework.context.annotation.EnableMBeanExport;
10 | import org.springframework.scheduling.annotation.EnableAsync;
11 | import org.springframework.transaction.annotation.EnableTransactionManagement;
12 | import springfox.documentation.swagger2.annotations.EnableSwagger2;
13 | import tk.mybatis.spring.annotation.MapperScan;
14 | @SpringBootApplication
15 | @ComponentScan("vip.codehome")
16 | @EnableSwagger2
17 | @EnableAsync
18 | @ServletComponentScan("vip.codehome.springboot.tutorials.filter")
19 | //@MapperScan(basePackages = "vip.codehome.springboot.tutorials.mapper")
20 | @EnableBatchProcessing
21 | @EnableTransactionManagement
22 | @EnableMBeanExport
23 | public class SpringbootTutorialsApplication {
24 |
25 | public static void main(String[] args) {
26 | SpringApplication.run(SpringbootTutorialsApplication.class, args);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/PropController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.beans.factory.annotation.Value;
5 | import org.springframework.web.bind.annotation.GetMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 | import vip.codehome.springboot.tutorials.common.R;
8 | import vip.codehome.springboot.tutorials.config.UserProperties;
9 | import vip.codehome.springboot.tutorials.entity.UserDO;
10 |
11 | import javax.validation.Valid;
12 | import java.util.Arrays;
13 | import java.util.List;
14 |
15 | @RestController
16 | public class PropController {
17 | float version;
18 | @Value("${author}")
19 | String author;
20 | @Value("${flag:true}")
21 | boolean flag;
22 | @Value("#{'${random}'.split(',')}")
23 | int[] randoms;
24 | @Autowired
25 | UserProperties userProperties;
26 | @GetMapping("/simple")
27 | public R propsSimple(){
28 | return R.ok(version);
29 | }
30 | @GetMapping("/object")
31 | public R propsObject(){
32 | System.out.println(userProperties.toString());
33 | return R.ok(userProperties.toString());
34 | }
35 | @GetMapping("/array")
36 | public R propsArray(){
37 | return R.ok(Arrays.toString(randoms));
38 | }
39 | @GetMapping("/jrebel")
40 | public R test(){
41 | return R.ok("");
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/dao/TkUserMapperTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.dao;
2 |
3 | import com.github.pagehelper.PageHelper;
4 | import com.github.pagehelper.PageInfo;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.test.context.junit4.SpringRunner;
10 | import vip.codehome.springboot.tutorials.entity.UserDO;
11 | import vip.codehome.springboot.tutorials.mapper.TkUserMapper;
12 |
13 | import java.util.List;
14 |
15 | @RunWith(SpringRunner.class)
16 | @SpringBootTest
17 | public class TkUserMapperTest {
18 | @Autowired
19 | TkUserMapper tkUserMapper;
20 | @Test
21 | public void add(){
22 | UserDO userDO=new UserDO();
23 | userDO.setId(1111L);
24 | userDO.setAge(11);
25 | userDO.setName("codehome");
26 | tkUserMapper.insert(userDO);
27 | }
28 | @Test
29 | public void pageTest(){
30 | PageHelper.startPage(0,10);
31 | List userDOList=tkUserMapper.selectAll();
32 | PageInfo userDOPageInfo=new PageInfo<>(userDOList);
33 | System.out.println(userDOPageInfo.getTotal());
34 | }
35 | @Test
36 | public void updateTest(){
37 | UserDO userDO=new UserDO();
38 | userDO.setId(1111L);
39 | userDO.setAge(22);
40 | userDO.setName("codehome");
41 | tkUserMapper.updateByPrimaryKey(userDO);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/es/ESLogCURDTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.es;
2 |
3 | import java.util.Date;
4 | import java.util.UUID;
5 | import org.junit.Test;
6 | import org.junit.runner.RunWith;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 | import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
10 | import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
11 | import org.springframework.data.elasticsearch.core.query.GetQuery;
12 | import org.springframework.data.elasticsearch.core.query.IndexQuery;
13 | import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
14 | import org.springframework.test.context.junit4.SpringRunner;
15 |
16 | /**
17 | * @author dsyslove@163.com
18 | * @createtime 2021/2/2--14:26
19 | * @description
20 | **/
21 | //@SpringBootTest
22 | //@RunWith(SpringRunner.class)
23 | public class ESLogCURDTest {
24 | @Autowired
25 | private ElasticsearchRestTemplate template;
26 | @Autowired
27 | LogRepository logRepository;
28 | @Test
29 | public void createIndex(){
30 | LogDO logDO=new LogDO();
31 | logDO.setId(UUID.randomUUID().toString());
32 | logDO.setMsgStatus("success");
33 | logDO.setLogTime(new Date());
34 | // logRepository.save(logDO);
35 | }
36 | @Test
37 | public void query(){
38 | IndexQuery indexQuery= new IndexQueryBuilder().withId("03946074-d9c2-45c5-a6ef-cb7153a13a14").build();
39 | template.index(indexQuery, IndexCoordinates.of("msglog"));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.scheduling.annotation.Async;
6 | import org.springframework.scheduling.annotation.EnableAsync;
7 | import org.springframework.stereotype.Component;
8 | import org.springframework.web.bind.annotation.*;
9 | import vip.codehome.springboot.tutorials.asynctask.UserServiceSyncTask;
10 | import vip.codehome.springboot.tutorials.common.R;
11 | import vip.codehome.springboot.tutorials.dto.LoginDTO;
12 | import vip.codehome.springboot.tutorials.entity.UserDO;
13 |
14 | import java.util.Arrays;
15 | import java.util.List;
16 | import java.util.concurrent.ExecutionException;
17 | import java.util.concurrent.Future;
18 |
19 | @RestController
20 | @RequestMapping("/user")
21 | @Slf4j
22 | public class UserController {
23 |
24 | @Autowired
25 | UserServiceSyncTask userServiceSyncTask;
26 |
27 | @GetMapping("/query")
28 | public String queryUser(String name) {
29 | return name;
30 | }
31 |
32 | @PostMapping("/add")
33 | public R addUser(@RequestBody UserDO userDO) {
34 | return R.ok(userDO);
35 | }
36 |
37 | @GetMapping("/cookie")
38 | public String testCookie(@CookieValue("token") String token) {
39 | return token;
40 | }
41 |
42 | @GetMapping("/sync")
43 | public R sync() throws ExecutionException, InterruptedException {
44 | log.info("进入到发送邮件方法....");
45 | userServiceSyncTask.sendEmail();
46 | Future res = userServiceSyncTask.echo("aa");
47 | return R.ok(res.get());
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/MvcController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.web.bind.annotation.*;
5 | import org.springframework.web.multipart.MultipartFile;
6 | import vip.codehome.springboot.tutorials.common.R;
7 | import vip.codehome.springboot.tutorials.entity.UserDO;
8 |
9 | import java.util.Map;
10 |
11 | @RestController
12 | public class MvcController {
13 |
14 | @GetMapping("/user/{id}")
15 | @ResponseBody
16 | public R userInfo(@PathVariable("id") String id) {
17 | return R.ok(id);
18 | }
19 |
20 | @GetMapping("/useragent")
21 | @ResponseBody
22 | public R getHeader(@RequestHeader("User-Agent") String userAgent) {
23 | return R.ok(userAgent);
24 | }
25 |
26 | @GetMapping("/cookie")
27 | @ResponseBody
28 | public R getCookie(@CookieValue("token") String token) {
29 | return R.ok(token);
30 | }
31 |
32 | @RequestMapping("/reqparam")
33 | @ResponseBody
34 | public R requsetParam(@RequestParam Map params) {
35 | return R.ok(params);
36 | }
37 |
38 | @RequestMapping("/upload")
39 | @ResponseBody
40 | public R requsetParam(@RequestParam("files") MultipartFile file,
41 | @RequestParam Map params) {
42 | params.put("files", file.getOriginalFilename());
43 | return R.ok(params);
44 | }
45 |
46 | @RequestMapping("/json")
47 | @ResponseBody
48 | public R json(@RequestBody UserDO userDO) {
49 | return R.ok(userDO);
50 | }
51 |
52 | @RequestMapping(value = "/xml", consumes = "application/xml", produces = "application/xml", method = RequestMethod.POST)
53 | @ResponseBody
54 | public UserDO xml(@RequestBody UserDO userDO) {
55 | return userDO;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/healthIndicator/MyEndpoint.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.healthIndicator;
2 |
3 | import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
4 | import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
5 | import org.springframework.boot.actuate.endpoint.annotation.Selector;
6 | import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
7 | import org.springframework.stereotype.Component;
8 |
9 | /***
10 | * @author 道士吟诗
11 | * @date 2021/5/7-下午10:46
12 | * @description
13 | * @Endpoint:定义一个监控端点,同时支持 HTTP 和 JMX 两种方式。
14 | * @WebEndpoint:定义一个监控端点,只支持 HTTP 方式。
15 | * @JmxEndpoint:定义一个监控端点,只支持 JMX 方式
16 | * @ReadOperation:作用在方法上,可用来返回端点展示的信息(通过 Get 方法请求)。
17 | * @WriteOperation:作用在方法上,可用来修改端点展示的信息(通过 Post 方法请求)。
18 | * @DeleteOperation:作用在方法上,可用来删除对应端点信息(通过 Delete 方法请求)。
19 | * @Selector:作用在参数上,用来定位一个端点的具体指标路由。
20 | ***/
21 | @Endpoint(id = "codehome")
22 | public class MyEndpoint {
23 | String blogUrl="www.codehome.vip";
24 | String author="dsys";
25 | @ReadOperation
26 | public String blog(){
27 | return blogUrl;
28 | }
29 | @ReadOperation
30 | public String author(){
31 | return author;
32 | }
33 | @ReadOperation
34 | public String test(@Selector String name){
35 | if("blog".equals(name)){
36 | return blogUrl;
37 | }
38 | if("author".equals(name)){
39 | return author;
40 | }
41 | return null;
42 | }
43 | @WriteOperation
44 | public void setConfigs(@Selector String name,String value){
45 | if("blog".equals(name)){
46 | this.blogUrl=value;
47 | }
48 | if("author".equals(name)){
49 | this.author=name;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/common/BusinessException.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.common;
2 |
3 | public class BusinessException extends RuntimeException {
4 |
5 | private static final long serialVersionUID = 1L;
6 | private int code = ApiCommonCodeEnum.FAIL.getCode();
7 | /**
8 | * 业务层异常 构造函数
9 | */
10 | public BusinessException() {
11 | }
12 |
13 | /**
14 | * 业务层异常 构造函数
15 | *
16 | * @param message 异常信息
17 | */
18 | public BusinessException(String message) {
19 | super(message);
20 | }
21 |
22 | /**
23 | * 业务层异常 构造函数
24 | *
25 | * @param cause Throwable
26 | */
27 | public BusinessException(Throwable cause) {
28 | super(cause);
29 | }
30 |
31 | /**
32 | * 业务层异常 构造函数
33 | *
34 | * @param message 异常信息
35 | * @param cause Throwable
36 | */
37 | public BusinessException(String message, Throwable cause) {
38 | super(message, cause);
39 | }
40 |
41 | /**
42 | * 业务层异常 构造函数
43 | *
44 | * @param code 异常代码
45 | * @param message 异常信息
46 | */
47 | public BusinessException(int code, String message) {
48 | super(message);
49 | this.code = (code == ApiCommonCodeEnum.OK.getCode() ? ApiCommonCodeEnum.FAIL.getCode() : code);
50 | }
51 |
52 | /**
53 | * 业务层异常 构造函数
54 | *
55 | * @param code 异常代码
56 | * @param message 异常信息
57 | * @param cause Throwable
58 | */
59 | public BusinessException(int code, String message, Throwable cause) {
60 | super(message, cause);
61 | this.code = (code == ApiCommonCodeEnum.OK.getCode() ? ApiCommonCodeEnum.FAIL.getCode() : code);
62 | }
63 |
64 | public int getCode() {
65 | return code;
66 | }
67 |
68 | }
69 |
70 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/scheduled/ScheduledTask.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.scheduled;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.beans.factory.annotation.Qualifier;
6 | import org.springframework.scheduling.annotation.EnableScheduling;
7 | import org.springframework.scheduling.annotation.Scheduled;
8 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
9 | import org.springframework.scheduling.config.ScheduledTaskRegistrar;
10 | import org.springframework.stereotype.Component;
11 |
12 | import java.util.concurrent.ScheduledThreadPoolExecutor;
13 |
14 | @Component
15 |
16 | @Slf4j
17 | public class ScheduledTask {
18 | @Scheduled(cron = "*/1 * * * * ?")
19 | public void cronTask1(){
20 | try {
21 | Thread.sleep(5100);
22 | } catch (InterruptedException e) {
23 | e.printStackTrace();
24 | }
25 | log.info("CronTask-当方法的执行时间超过任务调度频率时,调度器会在下个周期执行");
26 | }
27 | @Scheduled(fixedRate = 1000)
28 | public void cronTask2(){
29 | try {
30 | Thread.sleep(2100);
31 | } catch (InterruptedException e) {
32 | e.printStackTrace();
33 | }
34 | log.info("fixedRate--固定频率执行,当前执行任务如果超时,调度器会在当前方法执行完成后立即执行");
35 | }
36 | @Scheduled(fixedDelay = 1000)
37 | public void cronTask3(){
38 | try {
39 | Thread.sleep(2100);
40 | } catch (InterruptedException e) {
41 | e.printStackTrace();
42 | }
43 | log.info("fixedDelay---固定间隔执行,从上一次执行任务的结束时间开始算-------");
44 | // while (true){
45 | // try {
46 | // Thread.sleep(1000);
47 | // } catch (InterruptedException e) {
48 | // e.printStackTrace();
49 | // }
50 | // }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/handler/LogHandler.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.handler;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import org.springframework.core.NamedThreadLocal;
5 | import org.springframework.lang.Nullable;
6 | import org.springframework.web.servlet.HandlerInterceptor;
7 | import org.springframework.web.servlet.ModelAndView;
8 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
9 |
10 | import javax.servlet.http.HttpServletRequest;
11 | import javax.servlet.http.HttpServletResponse;
12 |
13 | /***
14 | *@author zyw
15 | *@createTime 2020/8/17 11:26
16 | *@description 单例
17 | *@version 1.0
18 | */
19 | @Slf4j
20 | public class LogHandler implements HandlerInterceptor {
21 | private NamedThreadLocal startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-StartTime");
22 |
23 | public LogHandler() {
24 | super();
25 | }
26 |
27 | @Override
28 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
29 | long beginTime = System.currentTimeMillis();//1、开始时间
30 | startTimeThreadLocal.set(beginTime);//线程绑定变量(该数据只有当前请求的线程可见)
31 | return true;//继续流程
32 | }
33 |
34 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
35 | }
36 |
37 | @Override
38 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
39 | long endTime = System.currentTimeMillis();
40 | long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量(开始时间)
41 | long consumeTime = endTime - beginTime;
42 | //3、消耗的时间
43 | log.info(String.format("%s consume %d millis", request.getRequestURI(), consumeTime));
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/config/logback-spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
9 |
10 |
11 | %black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable
12 |
13 |
14 |
15 |
16 |
18 | ${logPath}/${logName}
19 |
21 | %d %p %C{1.} [%t] %m%n
22 |
23 |
24 |
26 |
27 | ${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log
28 |
29 |
31 | 10MB
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/util/JsonUtil.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.util;
2 |
3 | import com.fasterxml.jackson.databind.DeserializationFeature;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 |
6 | import java.text.SimpleDateFormat;
7 | import java.util.ArrayList;
8 | import java.util.HashMap;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | /***
13 | *@author zyw
14 | *@createTime 2020/3/16 13:29
15 | *@description
16 | *@version 1.0
17 | */
18 | public class JsonUtil {
19 |
20 |
21 | private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
22 | private static final ObjectMapper mapper = new ObjectMapper();
23 |
24 | static {
25 | SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
26 | mapper.setDateFormat(dateFormat);
27 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
28 | }
29 |
30 | /**
31 | * 将json转换成
32 | *
33 | * @param json
34 | * @param valueType
35 | * @return
36 | * @author ZhiBing
37 | */
38 | public static T toObject(String json, Class valueType) {
39 | try {
40 | return (T) mapper.readValue(json, valueType);
41 | } catch (Exception e) {
42 | }
43 | return null;
44 | }
45 |
46 | @SuppressWarnings("unchecked")
47 | public static Map toMap(String json) {
48 | try {
49 | return mapper.readValue(json, Map.class);
50 | } catch (Exception e) {
51 | }
52 | return new HashMap();
53 | }
54 |
55 | @SuppressWarnings("rawtypes")
56 | public static List toList(String json) {
57 | try {
58 | return mapper.readValue(json, List.class);
59 | } catch (Exception e) {
60 | }
61 | return new ArrayList();
62 | }
63 |
64 |
65 | public static String toJson(Object obj) {
66 | try {
67 | return mapper.writeValueAsString(obj);
68 | } catch (Exception e) {
69 | }
70 | return "{}";
71 | }
72 |
73 |
74 |
75 |
76 |
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/controller/SwaggerUserController.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import io.swagger.annotations.*;
4 | import org.springframework.web.bind.annotation.*;
5 | import vip.codehome.springboot.tutorials.common.R;
6 | import vip.codehome.springboot.tutorials.dto.LoginDTO;
7 | import vip.codehome.springboot.tutorials.vo.UserInfoVO;
8 |
9 | import java.text.SimpleDateFormat;
10 | import java.util.Date;
11 |
12 | @RestController
13 | @Api(tags = "Swagger注解测试类")
14 | public class SwaggerUserController {
15 | @ApiOperation(value = "这是一个echo接口")
16 | @ApiImplicitParams({
17 | @ApiImplicitParam(name = "msg",value = "请求的msg参数",required = true,paramType = "query"),
18 | @ApiImplicitParam(name = "token",value = "请求的token",required = false,paramType ="header" )
19 | })
20 | @ApiResponses({
21 | @ApiResponse(code=200,message = "请求成功"),
22 | @ApiResponse(code=400,message="请求无权限")
23 | })
24 | @GetMapping("/echo")
25 | public R echo(String msg,@RequestHeader(name = "token") String token){
26 | return R.ok("");
27 | }
28 | @ApiOperation(value = "登录接口说明")
29 | @PostMapping("/login")
30 | public R login(@RequestBody LoginDTO loginDTO){
31 | UserInfoVO userInfoVO=new UserInfoVO();
32 | userInfoVO.setNickname("编程之家");
33 | userInfoVO.setToken("xxx");
34 | return R.ok(userInfoVO);
35 | }
36 | @GetMapping("/date")
37 | public R testDate(Date date){
38 | System.out.println(date);
39 | return R.ok(date);
40 | }
41 | @GetMapping("/date1")
42 | public R testDate(String date1){
43 | SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
44 | SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
45 | try {
46 | Date date = sdf1.parse(date1);//拿到Date对象
47 | String str = sdf2.format(date);//输出格式:2017-01-22 09:28:33
48 | System.out.println(str);
49 | return R.ok(date);
50 | } catch (Exception e) {
51 | e.printStackTrace();
52 | return R.failed("");
53 | }
54 |
55 |
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/ExceptionResolver.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import com.google.common.base.Charsets;
4 | import lombok.extern.slf4j.Slf4j;
5 | import org.springframework.stereotype.Component;
6 | import org.springframework.web.servlet.HandlerExceptionResolver;
7 | import org.springframework.web.servlet.ModelAndView;
8 | import vip.codehome.springboot.tutorials.common.BusinessException;
9 | import vip.codehome.springboot.tutorials.common.R;
10 | import vip.codehome.springboot.tutorials.util.ExUtil;
11 | import vip.codehome.springboot.tutorials.util.JsonUtil;
12 |
13 | import javax.servlet.http.HttpServletRequest;
14 | import javax.servlet.http.HttpServletResponse;
15 | import java.io.PrintWriter;
16 |
17 | @Component
18 | @Slf4j
19 | public class ExceptionResolver implements HandlerExceptionResolver {
20 | @Override
21 | public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
22 | if(ex instanceof BusinessException){
23 | R result= R.fill(((BusinessException) ex).getCode(),null,ex.getMessage());
24 | outputJSON(httpServletResponse, Charsets.UTF_8.toString(), JsonUtil.toJson(result));
25 | return null;
26 | }else {
27 | R result=R.failed(ex.getMessage());
28 | outputJSON(httpServletResponse, Charsets.UTF_8.toString(), JsonUtil.toJson(result));
29 | return null;
30 | }
31 | }
32 | private void outputJSON(HttpServletResponse response, String charset, String jsonStr) {
33 | PrintWriter out = null;
34 | try {
35 | if (response != null) {
36 | response.setCharacterEncoding(charset);
37 | response.setContentType("text/html;charset=" + charset);
38 | response.setHeader("Pragma", "No-cache");
39 | response.setHeader("Cache-Control", "no-cache");
40 | response.setDateHeader("Expires", 0);
41 | out = response.getWriter();
42 | out.print(jsonStr);
43 | }
44 | } catch (Exception e) {
45 | log.error(ExUtil.getSimpleMessage(e));
46 | } finally {
47 | if (out != null) {
48 | out.close();
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/SwaggerConfig.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
8 | import springfox.documentation.builders.ApiInfoBuilder;
9 | import springfox.documentation.builders.PathSelectors;
10 | import springfox.documentation.builders.RequestHandlerSelectors;
11 | import springfox.documentation.service.ApiInfo;
12 | import springfox.documentation.service.Contact;
13 | import springfox.documentation.spi.DocumentationType;
14 | import springfox.documentation.spring.web.plugins.Docket;
15 | import springfox.documentation.swagger2.annotations.EnableSwagger2;
16 |
17 | @EnableSwagger2
18 | @Configuration
19 | public class SwaggerConfig implements WebMvcConfigurer {
20 | @Bean
21 | public Docket createRestApi() {
22 | return new Docket(DocumentationType.SWAGGER_2)
23 | .apiInfo(apiInfo())
24 | .select()
25 | .apis(RequestHandlerSelectors.basePackage("vip.codehome.springboot.tutorials.controller"))
26 | .paths(PathSelectors.any())
27 | .build();
28 | }
29 | private ApiInfo apiInfo() {
30 | return new ApiInfoBuilder()
31 | .title("SpringBoot教程接口文档")//标题
32 | .description("使用swagger文档管理接口")//描述
33 | .contact(new Contact("codehome", "", "dsyslove@163.com"))//作者信息
34 | .version("1.0.0")//版本号
35 | .build();
36 | }
37 | @Override
38 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
39 | registry.addResourceHandler("/**").addResourceLocations(
40 | "classpath:/static/");
41 | registry.addResourceHandler("swagger-ui.html").addResourceLocations(
42 | "classpath:/META-INF/resources/");
43 | registry.addResourceHandler("doc.html").addResourceLocations(
44 | "classpath:/META-INF/resources/");
45 | registry.addResourceHandler("/webjars/**").addResourceLocations(
46 | "classpath:/META-INF/resources/webjars/");
47 |
48 | }
49 |
50 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SpringBoot Tutorial for Beginners
2 |
3 |
4 | ## 已完成系列
5 |
6 | - [x] [springboot2.x基础教程:快速开始](https://www.codehome.vip/archives/springboot-starter)
7 | - [x] [springboot2.x基础教程:配置文件详解](https://www.codehome.vip/archives/springboot-yml)
8 | - [x] [springboot2.x基础教程:接口实现统一格式返回](https://www.codehome.vip/archives/springboot-api)
9 | - [x] [SpringBoot2.x基础教程合集](https://www.codehome.vip/archives/springboot-all)
10 | - [x] [springboot2.x基础教程:Swagger详解给你的接口加上文档说明](https://www.codehome.vip/archives/springboot-swagger2)
11 | - [x] [springboot2.x基础教程:单元测试](https://www.codehome.vip/archives/springboot-test)
12 | - [x] [springboot2.x基础教程:jsr303接口参数校验,结合统一异常拦截](https://www.codehome.vip/archives/springboot-jsr303)
13 | - [x] [springboot2.x基础教程:JRebel实现SpringBoot热部署](https://www.codehome.vip/archives/springboot-jrebel)
14 | - [x] [springboot2.x基础教程:springmvc参数绑定注解今天彻底搞清楚](https://www.codehome.vip/archives/springmvc-prama-binding)
15 | - [x] [springboot2.x基础教程:过滤器和拦截器详解](https://www.codehome.vip/archives/springboot-filter)
16 | - [x] [springboot2.x基础教程:@Async开启异步任务](https://www.codehome.vip/archives/springboot-async)
17 | - [x] [springboot2.x基础教程:@Scheduled开启定时任务及源码分析](https://www.codehome.vip/archives/springboot定时任务)
18 | - [x] [springboot2.x基础教程:@Enable原理](https://www.codehome.vip/archives/springboot-enabled)
19 | - [x] [springboot2.x基础教程:集成mybatis最佳实践](https://www.codehome.vip/archives/springboot-mybatis)
20 | - [x] [springboot2.x基础教程:集成spring-data-jpa](https://www.codehome.vip/archives/springboot-jpa)
21 | - [x] [springboot2.x基础教程:动手制作一个starter包](https://www.codehome.vip/archives/springboot-starter-use)
22 | - [x] [springboot2.x基础教程:日志配置](https://www.codehome.vip/archives/springboot-logging)
23 | - [x] [springboot2.x基础教程:SpringCache缓存抽象详解与Ehcache、Redis缓存配置实战](https://www.codehome.vip/archives/springboot-cache)
24 | - [x] [SpringBoot2.x基础教程: 事件发布与订阅详解](https://www.codehome.vip/archives/springboot-sub-pub)
25 | - [x] [SpringBoot2.x基础教程: 事务详解](https://www.codehome.vip/archives/spring-transaction)
26 | - [x] [贡献一个springboot项目linux shell启动脚本](https://www.codehome.vip/archives/springboot-linux-starter)
27 | - [x] [SpringBoot通过proguard-maven-plugin插件进行实际项目代码混淆,实测可用](https://www.codehome.vip/archives/springboot-proguard)
28 | - [x] [SpringBoot项目瘦身打包](https://www.codehome.vip/archives/springboot-package)
29 | - [x] [SpringBoot2.x基础教程: 集成Quartz分布式任务调度](https://www.codehome.vip/archives/springboot-quartz)
30 | - [x] [SpringBoot2.x基础教程: 集成HirakiCP与Druid数据库连接池](https://www.codehome.vip/archives/springboot-datasource)
31 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/AsyncConfig.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import lombok.extern.slf4j.Slf4j;
4 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
5 | import org.springframework.context.annotation.Bean;
6 | import org.springframework.core.task.TaskExecutor;
7 | import org.springframework.scheduling.annotation.AsyncConfigurer;
8 | import org.springframework.scheduling.annotation.EnableAsync;
9 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
10 | import org.springframework.stereotype.Component;
11 |
12 | import java.lang.reflect.Method;
13 | import java.util.concurrent.Executor;
14 | import java.util.concurrent.ThreadPoolExecutor;
15 |
16 | @EnableAsync
17 | @Component
18 | @Slf4j
19 | public class AsyncConfig implements AsyncConfigurer {
20 | public TaskExecutor taskExecutor() {
21 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
22 | // 设置核心线程数
23 | executor.setCorePoolSize(8);
24 | // 设置最大线程数
25 | executor.setMaxPoolSize(16);
26 | // 设置队列容量
27 | executor.setQueueCapacity(50);
28 | // 设置线程活跃时间(秒)
29 | executor.setKeepAliveSeconds(60);
30 | //设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
31 | executor.setAwaitTerminationSeconds(60);
32 | // 设置默认线程名称
33 | executor.setThreadNamePrefix("CodehomeAsyncTask-");
34 | // 设置拒绝策略
35 | executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
36 | // 等待所有任务结束后再关闭线程池
37 | executor.setWaitForTasksToCompleteOnShutdown(true);
38 | executor.initialize();
39 | return executor;
40 | }
41 | public Executor getAsyncExecutor() {
42 | return taskExecutor();
43 | }
44 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
45 | return new MyAsyncExceptionHandler();
46 | }
47 |
48 | /**
49 | * 自定义异常处理类
50 | */
51 | class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
52 |
53 | @Override
54 | public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
55 | log.info("Exception message - " + throwable.getMessage());
56 | log.info("Method name - " + method.getName());
57 | for (Object param : objects) {
58 | log.info("Parameter value - " + param);
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/resources/mybatis-config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/transaction/UserServiceTranasction.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.transaction;
2 |
3 | import java.util.UUID;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.jdbc.core.JdbcTemplate;
6 | import org.springframework.stereotype.Service;
7 | import org.springframework.transaction.PlatformTransactionManager;
8 | import org.springframework.transaction.TransactionManager;
9 | import org.springframework.transaction.TransactionStatus;
10 | import org.springframework.transaction.annotation.Propagation;
11 | import org.springframework.transaction.annotation.Transactional;
12 | import org.springframework.transaction.support.DefaultTransactionDefinition;
13 | import org.springframework.transaction.support.TransactionTemplate;
14 |
15 | /**
16 | * @author dsyslove@163.com
17 | * @createtime 2021/4/6--13:58
18 | * @description
19 | * https://studygolang.com/articles/19133
20 | * https://www.huaweicloud.com/articles/df26a826898e8f02999f3bd861db3d48.html
21 | **/
22 | //@Service
23 | public class UserServiceTranasction {
24 | @Autowired
25 | JdbcTemplate jdbcTemplate;
26 | @Autowired
27 | TransactionTemplate transactionTemplate;
28 | @Autowired
29 | PlatformTransactionManager transactionManager;
30 | //声明式事务
31 | @Transactional(propagation = Propagation.REQUIRED,timeout = 3000,rollbackFor = Exception.class)
32 | public Integer save(Integer id,String name){
33 | String insertSql="insert into `tb_user`(`id`,`name`)values(?,?);";
34 | jdbcTemplate.update(insertSql,id,name);
35 | return jdbcTemplate.queryForObject("select count(*) from tb_user",Integer.class);
36 | }
37 | //编程式事务
38 | public Integer save1(Integer id,String name){
39 | Integer num=transactionTemplate.execute((TransactionStatus status)->{
40 | try{
41 | String insertSql="insert into `tb_user`(`id`,`name`)values(?,?);";
42 | jdbcTemplate.update(insertSql,id,name);
43 | }catch (Exception e){
44 | e.printStackTrace();
45 | //标记回滚
46 | status.setRollbackOnly();
47 | }
48 | return jdbcTemplate.queryForObject("select count(*) from tb_user",Integer.class);
49 | });
50 | return num;
51 | }
52 | //编程式事务
53 | public Integer save2(Integer id,String name){
54 | TransactionStatus transactionStatus=transactionManager.getTransaction(new DefaultTransactionDefinition());
55 | try{
56 | String insertSql="insert into `tb_user`(`id`,`name`)values(?,?);";
57 | jdbcTemplate.update(insertSql,id,name);
58 | transactionManager.commit(transactionStatus);
59 | }catch (Exception e){
60 | e.printStackTrace();
61 | transactionManager.rollback(transactionStatus);
62 | }
63 | return jdbcTemplate.queryForObject("select count(*) from tb_user",Integer.class);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/controller/UserControllerTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.controller;
2 |
3 | import net.minidev.json.JSONUtil;
4 | import org.junit.Assert;
5 | import org.junit.Before;
6 | import org.junit.jupiter.api.BeforeEach;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.runner.RunWith;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
11 | import org.springframework.boot.test.context.SpringBootTest;
12 | import org.springframework.http.MediaType;
13 | import org.springframework.test.context.junit4.SpringRunner;
14 | import org.springframework.test.web.servlet.MockMvc;
15 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
16 | import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
17 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
18 | import org.springframework.util.LinkedMultiValueMap;
19 | import org.springframework.util.MultiValueMap;
20 | import vip.codehome.springboot.tutorials.dto.LoginDTO;
21 | import vip.codehome.springboot.tutorials.entity.UserDO;
22 | import vip.codehome.springboot.tutorials.util.JsonUtil;
23 |
24 | import javax.servlet.http.Cookie;
25 |
26 | import static org.junit.jupiter.api.Assertions.*;
27 | @RunWith(SpringRunner.class)
28 | @SpringBootTest
29 | @AutoConfigureMockMvc
30 | class UserControllerTest {
31 | @Autowired
32 | MockMvc mockMvc;
33 | UserDO userDO;
34 | MultiValueMap params;
35 | @BeforeEach
36 | public void setUp()throws Exception{
37 | userDO=new UserDO();
38 | userDO.setPasswd("123456");
39 | params=new LinkedMultiValueMap<>();
40 | params.add("name","codehome");
41 | }
42 | @Test
43 | public void queryUser() throws Exception {
44 | String result= mockMvc.perform(MockMvcRequestBuilders.get("/user/query")
45 | .contentType(MediaType.APPLICATION_FORM_URLENCODED)
46 | .params(params)
47 | ).andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
48 | .andDo(MockMvcResultHandlers.print())
49 | .andReturn().getResponse()
50 | .getContentAsString();
51 | Assert.assertEquals("调用成功","codehome",result);
52 | }
53 |
54 | @Test
55 | void addUser() throws Exception {
56 | mockMvc.perform(MockMvcRequestBuilders.post("/user/add")
57 | .contentType(MediaType.APPLICATION_JSON)
58 | .content(JsonUtil.toJson(userDO))
59 | .accept(MediaType.APPLICATION_JSON)
60 | ).andExpect(MockMvcResultMatchers.status().is2xxSuccessful())
61 | .andDo(MockMvcResultHandlers.print())
62 | .andExpect(MockMvcResultMatchers.jsonPath("$.data.passwd").value("123456"));
63 | }
64 | @Test
65 | void testCookie()throws Exception{
66 | String token= mockMvc.perform(MockMvcRequestBuilders.get("/user/cookie")
67 | .cookie(new Cookie("token","123456")))
68 | .andDo(MockMvcResultHandlers.print())
69 | .andReturn().getResponse()
70 | .getContentAsString();
71 | Assert.assertEquals("token从cookie中获取成功","123456",token);
72 | }
73 | }
--------------------------------------------------------------------------------
/springboot-tutorials/src/test/java/vip/codehome/springboot/tutorials/dao/UserMapperTest.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.dao;
2 |
3 | import com.github.pagehelper.Page;
4 | import com.github.pagehelper.PageHelper;
5 | import com.github.pagehelper.PageInfo;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.boot.test.context.SpringBootTest;
10 | import org.springframework.test.context.junit4.SpringRunner;
11 | import vip.codehome.springboot.tutorials.entity.UserDO;
12 | import vip.codehome.springboot.tutorials.mapper.UserMapper;
13 |
14 | import java.time.LocalDateTime;
15 | import java.util.Arrays;
16 |
17 | @RunWith(SpringRunner.class)
18 | @SpringBootTest
19 | public class UserMapperTest {
20 | @Autowired
21 | UserMapper userMapper;
22 | //插入
23 | @Test
24 | public void testAdd(){
25 | UserDO userDO=new UserDO();
26 | userDO.setPasswd("codehome");
27 | userDO.setAccount("codehome");
28 | userDO.setName("name");
29 | userDO.setForbidden(true);
30 | userDO.setLoginTime(LocalDateTime.now());
31 | userMapper.insert(userDO);
32 | }
33 | //分页
34 | @Test
35 | public void page(){
36 | PageHelper.startPage(0,10);
37 | UserDO userDO=new UserDO();
38 | userDO.setName("n");
39 | PageInfo userDOPage= new PageInfo<>(userMapper.select(userDO));
40 | }
41 | //更新
42 | @Test
43 | public void update(){
44 | UserDO userDO=new UserDO();
45 | userDO.setId(1L);
46 | userDO.setName("编程之家");
47 | userMapper.update(userDO);
48 | }
49 | //删除
50 | @Test
51 | public void delete(){
52 | UserDO userDO=new UserDO();
53 | userDO.setId(1L);
54 | userMapper.delete(userDO);
55 | }
56 | //批量插入
57 | @Test
58 | public void testAddBatch(){
59 | UserDO userDO=new UserDO();
60 | userDO.setPasswd("codehome");
61 | userDO.setAccount("codehome");
62 | userDO.setName("name");
63 | userDO.setForbidden(true);
64 | userDO.setLoginTime(LocalDateTime.now());
65 | UserDO userDO1=new UserDO();
66 | userDO1.setPasswd("codehome");
67 | userDO1.setAccount("codehome");
68 | userDO1.setName("name");
69 | userDO1.setForbidden(true);
70 | userDO1.setLoginTime(LocalDateTime.now());
71 | userMapper.insertBatch(Arrays.asList(userDO,userDO1));
72 | }
73 | //批量更新
74 | @Test
75 | public void testUpdateBatch(){
76 | UserDO userDO=new UserDO();
77 | userDO.setPasswd("codehome1");
78 | userDO.setAccount("codehome1");
79 | userDO.setName("name1");
80 | userDO.setId(1L);
81 | userDO.setForbidden(true);
82 | userDO.setLoginTime(LocalDateTime.now());
83 | UserDO userDO1=new UserDO();
84 | userDO.setId(2L);
85 | userDO1.setPasswd("codehome2");
86 | userDO1.setAccount("codehome2");
87 | userDO1.setName("name2");
88 | userDO1.setForbidden(true);
89 | userDO1.setLoginTime(LocalDateTime.now());
90 | userMapper.insertBatch(Arrays.asList(userDO,userDO1));
91 | }
92 | //批量删除
93 | @Test
94 | public void deleteBatch(){
95 | userMapper.deleteBatch(new Long[]{1L,2L});
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/CustomRedisCacheManager.java:
--------------------------------------------------------------------------------
1 | package vip.codehome.springboot.tutorials.config;
2 |
3 | import org.springframework.cache.CacheManager;
4 | import org.springframework.cache.annotation.CachingConfigurerSupport;
5 | import org.springframework.cache.annotation.EnableCaching;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.data.redis.cache.RedisCacheConfiguration;
9 | import org.springframework.data.redis.cache.RedisCacheManager;
10 | import org.springframework.data.redis.cache.RedisCacheWriter;
11 | import org.springframework.data.redis.connection.RedisConnectionFactory;
12 | import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
13 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
14 | import org.springframework.data.redis.serializer.RedisSerializationContext;
15 | import org.springframework.data.redis.serializer.StringRedisSerializer;
16 |
17 | import java.time.Duration;
18 |
19 | /***
20 | *@author zyw
21 | *@createTime 2020/8/27 20:13
22 | *@description
23 | *@version 1.0
24 | */
25 | //@Configuration
26 | //@EnableCaching
27 | public class CustomRedisCacheManager extends CachingConfigurerSupport {
28 |
29 | @Bean
30 | public RedisCacheConfiguration redisCacheConfiguration(){
31 | Jackson2JsonRedisSerializer