├── 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 | -------------------------------------------------------------------------------- /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 | 8 | <#list userList> 9 |
    10 | <#items as user> 11 | ${user.loginTime}<#sep> 12 | 13 |
14 | 15 |

16 | <#if flag> 17 | flag is true 18 | <#else> 19 | flag is false 20 | 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 | 32 | <@test user=userList[0] remark="测试">插槽 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 jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); 32 | RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); 33 | configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).entryTtl(Duration.ofDays(30)); 34 | return configuration; 35 | } 36 | // @Bean 37 | // public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { 38 | // //初始化一个RedisCacheWriter 39 | // RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); 40 | // 41 | // Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); 42 | // 43 | // RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer(serializer); 44 | // 45 | // RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); 46 | // 47 | // return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); 48 | // } 49 | @Bean 50 | public CacheManager cacheManager(RedisConnectionFactory factory) { 51 | GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); 52 | StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); 53 | // 配置序列化 54 | RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); 55 | RedisCacheConfiguration redisCacheConfiguration = config 56 | // 键序列化方式 redis字符串序列化 57 | .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer)) 58 | // 值序列化方式 简单json序列化 59 | .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer)); 60 | return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build(); 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /springboot-tutorials/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | autoconfigure: 3 | exclude: 4 | - org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration 5 | - org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration 6 | - org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration 7 | - org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 8 | - tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration 9 | profiles: 10 | active: dev 11 | datasource: 12 | url: jdbc:mysql://localhost:3306/springboot?autoReconnect=true&useSSL=false&characterEncoding=utf-8&failOverReadOnly=false&allowPublicKeyRetrieval=true&allowMultiQueries=true 13 | username: root 14 | password: 123456 15 | driver-class-name: com.mysql.cj.jdbc.Driver 16 | hikari: 17 | auto-commit: true 18 | servlet: 19 | multipart: 20 | max-request-size: 20MB 21 | max-file-size: 20MB 22 | jpa: 23 | hibernate: 24 | ddl-auto: update 25 | #设置数据库方言 26 | database-platform: org.hibernate.dialect.MySQL5InnoDBDialect 27 | #打印sql 28 | show-sql: true 29 | batch: 30 | initialize-schema: always 31 | job: 32 | enabled: false #禁止自动执行job需要调用obLaucher.run执行 33 | lifecycle: 34 | timeout-per-shutdown-phase: 15s 35 | freemarker: 36 | cache: true 37 | suffix: .ftl 38 | template-loader-path: 39 | - classpath:/templates 40 | elasticsearch: 41 | rest: 42 | uris: http://localhost:9200 43 | redis: 44 | timeout: 5000ms 45 | lettuce: 46 | pool: 47 | max-active: 5 48 | max-wait: -1 49 | max-idle: 10 50 | host: localhost 51 | cache: 52 | ehcache: 53 | config: classpath:ehcache.xml 54 | type: redis 55 | mybatis: 56 | config-location: classpath:mybatis-config.xml 57 | mapper-locations: classpath:mappers/*.xml 58 | type-aliases-package: vip.codehome.springboot.tutorials.entity 59 | mapper: 60 | mappers: 61 | - tk.mybatis.mapper.common.Mapper 62 | not-empty: false 63 | identity: MYSQL 64 | pagehelper: 65 | helperDialect: mysql 66 | reasonable: true 67 | supportMethodsArguments: true 68 | params: count=countSql 69 | logging: 70 | level: 71 | #包的日志级别 72 | org.springframework.web: DEBUG 73 | #自定义log信息 74 | config: classpath:config/logback-spring.xml 75 | pattern: 76 | #控制台的日志输出格式 77 | console: '%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n' 78 | #文件的日志输出格式 79 | file: '%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n' 80 | file: 81 | #日志名称 82 | name: app.log 83 | #存储的路径 84 | path: logs 85 | #存储的最大值 86 | max-size: 50MB 87 | #保存时间 88 | max-history: 7 89 | management: 90 | endpoints: 91 | web: 92 | exposure: 93 | include: "*" 94 | endpoint: 95 | health: 96 | show-details: always 97 | health: 98 | db: 99 | enabled: true 100 | elasticsearch: 101 | enabled: false 102 | version: 1.0 103 | author: codhome.vip 104 | flag: true 105 | user: 106 | userName: codehome 107 | age: 18 108 | forbidden: true 109 | random: 10,20,30 110 | random1: 111 | user: 112 | - zhangsao 113 | - lisi 114 | - wangwu 115 | --- 116 | 117 | #配置开发环境 118 | spring: 119 | profiles: dev 120 | server: 121 | port: 9000 122 | #开启优雅关闭 123 | shutdown: graceful 124 | --- 125 | 126 | #配置生产环境 127 | spring: 128 | profiles: prod 129 | server: 130 | port: 9100 131 | debug: true -------------------------------------------------------------------------------- /springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/transaction/TxAdviceInterceptor.java: -------------------------------------------------------------------------------- 1 | package vip.codehome.springboot.tutorials.transaction; 2 | 3 | import java.util.Collections; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import javax.sql.DataSource; 7 | import org.aspectj.lang.annotation.Aspect; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.aop.Advisor; 11 | import org.springframework.aop.aspectj.AspectJExpressionPointcut; 12 | import org.springframework.aop.support.DefaultPointcutAdvisor; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.beans.factory.annotation.Value; 15 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 16 | import org.springframework.context.annotation.Bean; 17 | import org.springframework.context.annotation.Configuration; 18 | import org.springframework.stereotype.Component; 19 | import org.springframework.transaction.PlatformTransactionManager; 20 | import org.springframework.transaction.TransactionDefinition; 21 | import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource; 22 | import org.springframework.transaction.interceptor.RollbackRuleAttribute; 23 | import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute; 24 | import org.springframework.transaction.interceptor.TransactionAttribute; 25 | import org.springframework.transaction.interceptor.TransactionInterceptor; 26 | 27 | /** 28 | * @author dsyslove@163.com 29 | * @createtime 2021/4/6--18:24 30 | * @description 31 | **/ 32 | //@Aspect 33 | //@Component //事务依然生效 34 | //@Configuration("__tx_advice_interceptor__") 35 | //@ConditionalOnBean(DataSource.class) 36 | public class TxAdviceInterceptor { 37 | 38 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 39 | @Value("${tx.timeout:5}") 40 | private int TX_METHOD_TIMEOUT = 5; 41 | private String AOP_POINTCUT_EXPRESSION = "execution(* codehome.vip.*.service.*.*(..)) "; 42 | @Autowired 43 | private PlatformTransactionManager transactionManager; 44 | 45 | @Bean 46 | public TransactionInterceptor txAdvice() { 47 | NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource(); 48 | /*只读事务,不做更新操作*/ 49 | RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute(); 50 | readOnlyTx.setReadOnly(true); 51 | readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); 52 | /*当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务*/ 53 | RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute(); 54 | requiredTx.setRollbackRules( 55 | Collections.singletonList(new RollbackRuleAttribute(Exception.class))); 56 | requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); 57 | requiredTx.setTimeout(TX_METHOD_TIMEOUT); 58 | Map txMap = new HashMap<>(); 59 | txMap.put("save*", requiredTx); 60 | txMap.put("update*", requiredTx); 61 | txMap.put("remove*", requiredTx); 62 | txMap.put("*", readOnlyTx); 63 | source.setNameMap(txMap); 64 | TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source); 65 | if (logger.isInfoEnabled()) { 66 | logger.info("事务管理器启动成功!"); 67 | } 68 | return txAdvice; 69 | } 70 | 71 | @Bean 72 | public Advisor txAdviceAdvisor() { 73 | AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); 74 | pointcut.setExpression(AOP_POINTCUT_EXPRESSION); 75 | return new DefaultPointcutAdvisor(pointcut, txAdvice()); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/util/ExUtil.java: -------------------------------------------------------------------------------- 1 | package vip.codehome.springboot.tutorials.util; 2 | 3 | import org.springframework.util.StringUtils; 4 | import vip.codehome.springboot.tutorials.common.BusinessException; 5 | 6 | import java.io.PrintStream; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.UndeclaredThrowableException; 9 | import java.util.ArrayList; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | public class ExUtil { 15 | public static void throwBusException(String msg){ 16 | throw new BusinessException(msg); 17 | } 18 | public static String getSimpleMessage(Throwable e) { 19 | return null == e ? "null" : e.getMessage(); 20 | } 21 | public static RuntimeException wrapRuntime(Throwable throwable) { 22 | return throwable instanceof RuntimeException ? (RuntimeException)throwable : new RuntimeException(throwable); 23 | } 24 | 25 | public static void wrapAndThrow(Throwable throwable) { 26 | if (throwable instanceof RuntimeException) { 27 | throw (RuntimeException)throwable; 28 | } else if (throwable instanceof Error) { 29 | throw (Error)throwable; 30 | } else { 31 | throw new UndeclaredThrowableException(throwable); 32 | } 33 | } 34 | 35 | public static Throwable unwrap(Throwable wrapped) { 36 | Throwable unwrapped = wrapped; 37 | 38 | while(true) { 39 | while(!(unwrapped instanceof InvocationTargetException)) { 40 | if (!(unwrapped instanceof UndeclaredThrowableException)) { 41 | return unwrapped; 42 | } 43 | 44 | unwrapped = ((UndeclaredThrowableException)unwrapped).getUndeclaredThrowable(); 45 | } 46 | 47 | unwrapped = ((InvocationTargetException)unwrapped).getTargetException(); 48 | } 49 | } 50 | 51 | public static StackTraceElement[] getStackElements() { 52 | return Thread.currentThread().getStackTrace(); 53 | } 54 | 55 | public static StackTraceElement getStackElement(int i) { 56 | return getStackElements()[i]; 57 | } 58 | 59 | public static StackTraceElement getRootStackElement() { 60 | StackTraceElement[] stackElements = getStackElements(); 61 | return stackElements[stackElements.length - 1]; 62 | } 63 | 64 | 65 | 66 | public static boolean isCausedBy(Throwable throwable, Class... causeClasses) { 67 | return null != getCausedBy(throwable, causeClasses); 68 | } 69 | 70 | public static Throwable getCausedBy(Throwable throwable, Class... causeClasses) { 71 | for(Throwable cause = throwable; cause != null; cause = cause.getCause()) { 72 | Class[] var3 = causeClasses; 73 | int var4 = causeClasses.length; 74 | 75 | for(int var5 = 0; var5 < var4; ++var5) { 76 | Class causeClass = var3[var5]; 77 | if (causeClass.isInstance(cause)) { 78 | return cause; 79 | } 80 | } 81 | } 82 | 83 | return null; 84 | } 85 | 86 | 87 | public static List getThrowableList(Throwable throwable) { 88 | ArrayList list; 89 | for(list = new ArrayList(); throwable != null && !list.contains(throwable); throwable = throwable.getCause()) { 90 | list.add(throwable); 91 | } 92 | 93 | return list; 94 | } 95 | 96 | public static Throwable getRootCause(Throwable throwable) { 97 | List list = getThrowableList(throwable); 98 | return list.size() < 1 ? null : (Throwable)list.get(list.size() - 1); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /springboot-tutorials/src/main/resources/mappers/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | id,name,account,age,forbidden,login_time,passwd 6 | 7 | 8 | insert into tb_user( 9 | 10 | id, 11 | account, 12 | passwd, 13 | name, 14 | 15 | age, 16 | 17 | 18 | forbidden, 19 | 20 | 21 | login_time, 22 | 23 | 24 | )values ( 25 | 26 | #{id}, 27 | #{account}, 28 | #{passwd}, 29 | #{name}, 30 | 31 | #{age}, 32 | 33 | 34 | #{forbidden}, 35 | 36 | 37 | #{loginTime}, 38 | 39 | 40 | ) 41 | 42 | 55 | 56 | update tb_user 57 | 58 | 59 | name=#{name}, 60 | 61 | 62 | age=#{age} 63 | 64 | 65 | where id=#{id} 66 | 67 | 68 | 69 | delete from tb_user where id=#{id} 70 | 71 | 72 | 73 | SELECT 74 | LAST_INSERT_ID() 75 | 76 | insert into tb_user( 77 | account,passwd,name,age,forbidden,login_time 78 | )values 79 | 80 | (#{user.account}, 81 | #{user.passwd}, 82 | #{user.name}, 83 | #{user.age}, 84 | #{user.forbidden}, 85 | #{user.loginTime}) 86 | 87 | 88 | 89 | 90 | 91 | update tb_user 92 | 93 | 94 | name=#{name}, 95 | 96 | 97 | age=#{age} 98 | 99 | 100 | where id=#{id} 101 | 102 | 103 | 104 | delete from tb_user 105 | where id in 106 | 107 | #{id} 108 | 109 | 110 | -------------------------------------------------------------------------------- /springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/batch/BatchJobConfig.java: -------------------------------------------------------------------------------- 1 | package vip.codehome.springboot.tutorials.batch; 2 | 3 | import org.springframework.batch.core.ExitStatus; 4 | import org.springframework.batch.core.Job; 5 | import org.springframework.batch.core.Step; 6 | import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; 7 | import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; 8 | import org.springframework.batch.item.database.JdbcPagingItemReader; 9 | import org.springframework.batch.item.database.Order; 10 | import org.springframework.batch.item.database.support.MySqlPagingQueryProvider; 11 | import org.springframework.batch.item.file.FlatFileItemReader; 12 | import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; 13 | import org.springframework.batch.item.file.transform.FixedLengthTokenizer; 14 | import org.springframework.batch.repeat.RepeatStatus; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.context.annotation.Bean; 17 | import org.springframework.context.annotation.Configuration; 18 | import org.springframework.core.io.ClassPathResource; 19 | import org.springframework.jdbc.core.BeanPropertyRowMapper; 20 | import vip.codehome.springboot.tutorials.entity.UserDO; 21 | 22 | import javax.sql.DataSource; 23 | import java.util.HashMap; 24 | 25 | /** 26 | * https://mrbird.cc/Spring-Batch%E5%85%A5%E9%97%A8.html 27 | * https://segmentfault.com/a/1190000024439130 28 | */ 29 | //@Configuration 30 | public class BatchJobConfig { 31 | 32 | @Bean 33 | public JdbcPagingItemReader jdbcPagingItemTbUserReader(DataSource dataSource) { 34 | JdbcPagingItemReader reader = new JdbcPagingItemReader<>(); 35 | reader.setDataSource(dataSource); 36 | reader.setFetchSize(100); 37 | 38 | reader.setQueryProvider(new MySqlPagingQueryProvider() {{ 39 | setSelectClause("select id,account,age,name,login_time,forbidden"); 40 | setFromClause("from tb_user"); 41 | setWhereClause("age>:age"); 42 | setSortKeys(new HashMap() {{ 43 | put("person_id", Order.ASCENDING); 44 | }}); 45 | }}); 46 | reader.setParameterValues(new HashMap() {{ 47 | put("age", 20); 48 | }}); 49 | reader.setRowMapper(new BeanPropertyRowMapper<>(UserDO.class)); 50 | return reader; 51 | } 52 | 53 | @Autowired 54 | private JobBuilderFactory jobBuilderFactory; 55 | @Autowired 56 | private StepBuilderFactory stepBuilderFactory; 57 | 58 | @Bean 59 | public Job multiStepJob() { 60 | return jobBuilderFactory.get("multiStepJob2") 61 | .start(step1()) 62 | .on(ExitStatus.COMPLETED.getExitCode()).to(step2()) 63 | .from(step2()) 64 | .on(ExitStatus.COMPLETED.getExitCode()).to(step3()) 65 | .from(step3()).end() 66 | .build(); 67 | } 68 | 69 | private Step step1() { 70 | return stepBuilderFactory.get("step1") 71 | .tasklet((stepContribution, chunkContext) -> { 72 | System.out.println("执行步骤一操作。。。"); 73 | return RepeatStatus.FINISHED; 74 | }).build(); 75 | } 76 | 77 | private Step step2() { 78 | return stepBuilderFactory.get("step2") 79 | .tasklet((stepContribution, chunkContext) -> { 80 | System.out.println("执行步骤二操作。。。"); 81 | return RepeatStatus.FINISHED; 82 | }).build(); 83 | } 84 | 85 | private Step step3() { 86 | return stepBuilderFactory.get("step3") 87 | .tasklet((stepContribution, chunkContext) -> { 88 | System.out.println("执行步骤三操作。。。"); 89 | return RepeatStatus.FINISHED; 90 | }).build(); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package vip.codehome.springboot.tutorials.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 4 | import com.fasterxml.jackson.annotation.PropertyAccessor; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.cache.Cache; 9 | import org.springframework.cache.CacheManager; 10 | import org.springframework.cache.annotation.CachingConfigurerSupport; 11 | import org.springframework.cache.annotation.EnableCaching; 12 | import org.springframework.cache.interceptor.CacheErrorHandler; 13 | import org.springframework.cache.interceptor.KeyGenerator; 14 | import org.springframework.context.annotation.Bean; 15 | import org.springframework.context.annotation.Configuration; 16 | import org.springframework.data.redis.cache.CacheKeyPrefix; 17 | import org.springframework.data.redis.cache.RedisCacheConfiguration; 18 | import org.springframework.data.redis.cache.RedisCacheManager; 19 | import org.springframework.data.redis.cache.RedisCacheWriter; 20 | import org.springframework.data.redis.connection.RedisConnectionFactory; 21 | import org.springframework.data.redis.core.RedisTemplate; 22 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 23 | import org.springframework.data.redis.serializer.RedisSerializationContext; 24 | 25 | import java.lang.reflect.Method; 26 | import java.time.Duration; 27 | import java.util.Arrays; 28 | import java.util.HashMap; 29 | import java.util.Map; 30 | import java.util.stream.Collectors; 31 | 32 | /*** 33 | *@author zyw 34 | *@createTime 2020/8/28 15:41 35 | *@description 36 | *@version 1.0 37 | */ 38 | //@Configuration 39 | @EnableCaching//开启缓存 40 | public class RedisConfig extends CachingConfigurerSupport { 41 | 42 | private final static Logger log= LoggerFactory.getLogger(RedisConfig.class); 43 | 44 | @Bean 45 | public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { 46 | 47 | return new RedisCacheManager( 48 | RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), 49 | this.getRedisCacheConfigurationWithTtl(60*60*24), // 默认策略,未配置的 key 会使用这个 50 | this.getRedisCacheConfigurationMap() // 指定 key 策略 51 | ); 52 | } 53 | 54 | private Map getRedisCacheConfigurationMap() { 55 | Map redisCacheConfigurationMap = new HashMap<>(); 56 | //可以进行过期时间配置 57 | redisCacheConfigurationMap.put("24h", this.getRedisCacheConfigurationWithTtl(60*60*24)); 58 | redisCacheConfigurationMap.put("30d", this.getRedisCacheConfigurationWithTtl(60*60*24*30)); 59 | return redisCacheConfigurationMap; 60 | } 61 | 62 | private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { 63 | Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); 64 | ObjectMapper om = new ObjectMapper(); 65 | om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 66 | om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 67 | jackson2JsonRedisSerializer.setObjectMapper(om); 68 | 69 | RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); 70 | 71 | redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( 72 | RedisSerializationContext 73 | .SerializationPair 74 | .fromSerializer(jackson2JsonRedisSerializer) 75 | ).entryTtl(Duration.ofSeconds(seconds)); 76 | 77 | //自定义前缀 默认为中间两个: 78 | redisCacheConfiguration = redisCacheConfiguration.computePrefixWith(myKeyPrefix()); 79 | 80 | return redisCacheConfiguration; 81 | } 82 | 83 | /** 84 | * 缓存前缀(追加一个冒号 : ) 85 | * @return 86 | */ 87 | private CacheKeyPrefix myKeyPrefix(){ 88 | return (name) -> { 89 | return name +":"; 90 | }; 91 | } 92 | 93 | /** 94 | * 生成Key规则 95 | * @return 96 | */ 97 | @Bean 98 | public KeyGenerator wiselyKeyGenerator() { 99 | return new KeyGenerator() { 100 | @Override 101 | public Object generate(Object target, Method method, Object... params) { 102 | StringBuilder sb = new StringBuilder(); 103 | sb.append(target.getClass().getName()); 104 | sb.append("." + method.getName()); 105 | if(params==null||params.length==0||params[0]==null){ 106 | return null; 107 | } 108 | String join = String.join("&", Arrays.stream(params).map(Object::toString).collect(Collectors.toList())); 109 | String format = String.format("%s{%s}", sb.toString(), join); 110 | //log.info("缓存key:" + format); 111 | return format; 112 | } 113 | }; 114 | } 115 | 116 | @Bean 117 | public RedisTemplate redisTemplate(RedisConnectionFactory factory) { 118 | RedisTemplate redisTemplate = new RedisTemplate(); 119 | redisTemplate.setConnectionFactory(factory); 120 | return redisTemplate; 121 | } 122 | 123 | 124 | /** 125 | * 缓存异常处理 126 | * @return 127 | */ 128 | @Bean 129 | @Override 130 | public CacheErrorHandler errorHandler() { 131 | CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() { 132 | @Override 133 | public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { 134 | log.info("redis缓存获取异常:"+ key); 135 | } 136 | 137 | @Override 138 | public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { 139 | log.info("redis缓存添加异常:"+ key); 140 | } 141 | 142 | @Override 143 | public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { 144 | log.info("redis缓存删除异常:"+ key); 145 | } 146 | 147 | @Override 148 | public void handleCacheClearError(RuntimeException e, Cache cache) { 149 | log.info("redis缓存清理异常"); 150 | } 151 | }; 152 | return cacheErrorHandler; 153 | } 154 | 155 | 156 | } 157 | -------------------------------------------------------------------------------- /springboot-tutorials/src/main/java/vip/codehome/springboot/tutorials/asyncrequest/AsyncRequsetDemoController.java: -------------------------------------------------------------------------------- 1 | package vip.codehome.springboot.tutorials.asyncrequest; 2 | 3 | import static org.springframework.web.bind.annotation.RequestMethod.GET; 4 | 5 | import com.google.common.util.concurrent.ThreadFactoryBuilder; 6 | import java.io.IOException; 7 | import java.util.concurrent.Callable; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.ScheduledExecutorService; 10 | import java.util.concurrent.ScheduledThreadPoolExecutor; 11 | import java.util.concurrent.ThreadFactory; 12 | import java.util.concurrent.ThreadPoolExecutor; 13 | import java.util.concurrent.TimeUnit; 14 | import javax.annotation.Resource; 15 | import javax.servlet.AsyncContext; 16 | import javax.servlet.AsyncEvent; 17 | import javax.servlet.AsyncListener; 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | import lombok.extern.slf4j.Slf4j; 21 | import org.springframework.context.annotation.Bean; 22 | import org.springframework.context.annotation.Configuration; 23 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 24 | import org.springframework.web.bind.annotation.GetMapping; 25 | import org.springframework.web.bind.annotation.RequestMapping; 26 | import org.springframework.web.bind.annotation.ResponseBody; 27 | import org.springframework.web.bind.annotation.RestController; 28 | import org.springframework.web.context.request.async.DeferredResult; 29 | import org.springframework.web.context.request.async.TimeoutCallableProcessingInterceptor; 30 | import org.springframework.web.context.request.async.WebAsyncTask; 31 | import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; 32 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 33 | 34 | /** 35 | * @author zyw 36 | * @mail dsyslove@163.com 37 | * @createtime 2021/5/18--15:38 38 | * @description 39 | **/ 40 | @RestController 41 | @Slf4j 42 | public class AsyncRequsetDemoController { 43 | private ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("longPolling-timeout-checker-%d") 44 | .build(); 45 | private ScheduledExecutorService timeoutChecker = new ScheduledThreadPoolExecutor(1, threadFactory); 46 | @GetMapping("/asynccontext") 47 | public void asyncContext(HttpServletRequest request, HttpServletResponse response){ 48 | AsyncContext asyncContext=request.startAsync(); 49 | asyncContext.addListener(new AsyncListener() { 50 | @Override 51 | public void onComplete(AsyncEvent event) throws IOException { 52 | System.out.println("执行完成"); 53 | } 54 | 55 | @Override 56 | public void onTimeout(AsyncEvent event) throws IOException { 57 | System.out.println("超时了"); 58 | } 59 | 60 | @Override 61 | public void onError(AsyncEvent event) throws IOException { 62 | System.out.println("发生错误"); 63 | } 64 | 65 | @Override 66 | public void onStartAsync(AsyncEvent event) throws IOException { 67 | System.out.println("异步请求开始"); 68 | } 69 | }); 70 | // asyncContext.start(()->{ 71 | // try { 72 | // //长时间耗时服务 73 | // asyncContext.getResponse().getWriter().write("hello async"); 74 | // } catch (IOException e) { 75 | // e.printStackTrace(); 76 | // } 77 | // asyncContext.complete(); 78 | // }); 79 | //不用start创建的线程 80 | // Runnable runnable=()->{ 81 | // try { 82 | // //长时间耗时服务 83 | // asyncContext.getResponse().getWriter().write("hello async"); 84 | // } catch (IOException e) { 85 | // e.printStackTrace(); 86 | // } 87 | // asyncContext.complete(); 88 | // }; 89 | // new Thread(runnable).start(); 90 | //使用线程池 91 | timeoutChecker.submit(()->{ 92 | try { 93 | //长时间耗时服务 94 | asyncContext.getResponse().getWriter().write("hello async"); 95 | } catch (IOException e) { 96 | e.printStackTrace(); 97 | } 98 | asyncContext.complete(); 99 | }); 100 | } 101 | @RequestMapping(value = "/email/callableReq", method = GET) 102 | @ResponseBody 103 | public Callable callableReq () { 104 | System.out.println("外部线程:" + Thread.currentThread().getName()); 105 | 106 | return new Callable() { 107 | 108 | @Override 109 | public String call() throws Exception { 110 | Thread.sleep(10000); 111 | System.out.println("内部线程:" + Thread.currentThread().getName()); 112 | return "callable!"; 113 | } 114 | }; 115 | } 116 | 117 | @Configuration 118 | public class RequestAsyncPoolConfig extends WebMvcConfigurerAdapter { 119 | 120 | @Resource 121 | private ThreadPoolTaskExecutor myThreadPoolTaskExecutor; 122 | 123 | @Override 124 | public void configureAsyncSupport(final AsyncSupportConfigurer configurer) { 125 | //处理 callable超时 126 | configurer.setDefaultTimeout(60*1000); 127 | configurer.setTaskExecutor(myThreadPoolTaskExecutor); 128 | configurer.registerCallableInterceptors(timeoutCallableProcessingInterceptor()); 129 | } 130 | 131 | @Bean 132 | public TimeoutCallableProcessingInterceptor timeoutCallableProcessingInterceptor() { 133 | return new TimeoutCallableProcessingInterceptor(); 134 | } 135 | } 136 | 137 | @RequestMapping(value = "/email/webAsyncReq", method = GET) 138 | @ResponseBody 139 | public WebAsyncTask webAsyncReq () { 140 | System.out.println("外部线程:" + Thread.currentThread().getName()); 141 | Callable result = () -> { 142 | System.out.println("内部线程开始:" + Thread.currentThread().getName()); 143 | try { 144 | TimeUnit.SECONDS.sleep(4); 145 | } catch (Exception e) { 146 | // TODO: handle exception 147 | } 148 | log.info("副线程返回"); 149 | System.out.println("内部线程返回:" + Thread.currentThread().getName()); 150 | return "success"; 151 | }; 152 | WebAsyncTask wat = new WebAsyncTask(3000L, result); 153 | wat.onTimeout(new Callable() { 154 | @Override 155 | public String call() throws Exception { 156 | // TODO Auto-generated method stub 157 | return "超时"; 158 | } 159 | }); 160 | return wat; 161 | } 162 | @RequestMapping(value = "/email/deferredResultReq", method = GET) 163 | @ResponseBody 164 | public DeferredResult deferredResultReq () { 165 | System.out.println("外部线程:" + Thread.currentThread().getName()); 166 | //设置超时时间 167 | DeferredResult result = new DeferredResult(60*1000L); 168 | //处理超时事件 采用委托机制 169 | result.onTimeout(new Runnable() { 170 | 171 | @Override 172 | public void run() { 173 | System.out.println("DeferredResult超时"); 174 | result.setResult("超时了!"); 175 | } 176 | }); 177 | result.onCompletion(new Runnable() { 178 | 179 | @Override 180 | public void run() { 181 | //完成后 182 | System.out.println("调用完成"); 183 | } 184 | }); 185 | timeoutChecker.execute(new Runnable() { 186 | @Override 187 | public void run() { 188 | //处理业务逻辑 189 | System.out.println("内部线程:" + Thread.currentThread().getName()); 190 | //返回结果 191 | result.setResult("DeferredResult!!"); 192 | } 193 | }); 194 | return result; 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /springboot-tutorials/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.3.2.RELEASE 9 | 10 | 11 | vip.codehome 12 | springboot-tutorials 13 | 0.0.1-SNAPSHOT 14 | springboot-tutorials 15 | SpringBoot2.x基础教程 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-web 25 | 26 | 27 | io.springfox 28 | springfox-swagger2 29 | 2.9.2 30 | 31 | 32 | io.springfox 33 | springfox-swagger-ui 34 | 2.9.2 35 | 36 | 37 | org.projectlombok 38 | lombok 39 | 1.18.12 40 | compile 41 | 42 | 43 | com.github.xiaoymin 44 | knife4j-spring-ui 45 | 2.0.4 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-validation 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-data-jpa 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-data-elasticsearch 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | mysql 72 | mysql-connector-java 73 | runtime 74 | 75 | 76 | 77 | org.springframework.boot 78 | spring-boot-starter-actuator 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | com.github.pagehelper 89 | pagehelper 90 | 5.1.2 91 | 92 | 93 | org.springframework.boot 94 | spring-boot-starter-cache 95 | 96 | 97 | net.sf.ehcache 98 | ehcache 99 | 100 | 101 | org.springframework.boot 102 | spring-boot-starter-data-redis 103 | 104 | 105 | org.apache.commons 106 | commons-pool2 107 | 2.6.2 108 | 109 | 110 | org.springframework.boot 111 | spring-boot-starter-freemarker 112 | 113 | 114 | tk.mybatis 115 | mapper-spring-boot-starter 116 | 2.1.5 117 | 118 | 119 | org.springframework.boot 120 | spring-boot-starter-batch 121 | 122 | 123 | org.jolokia 124 | jolokia-core 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | org.apache.maven.plugins 137 | maven-jar-plugin 138 | 139 | 140 | 141 | false 142 | 143 | 144 | true 145 | 146 | lib/ 147 | 148 | vip.codehome.springboot.tutorials.SpringbootTutorialsApplication 149 | 150 | 151 | 152 | 153 | 154 | 155 | org.apache.maven.plugins 156 | maven-dependency-plugin 157 | 158 | 159 | copy-lib 160 | package 161 | 162 | copy-dependencies 163 | 164 | 165 | target/lib 166 | false 167 | false 168 | runtime 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | -------------------------------------------------------------------------------- /springboot-tutorials/intellij-java-google-style.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | 21 | 28 | 599 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------