QuickStart is a loading method used by several different software applications, designed to speed up the loading time of their software. Some load the core files and libraries during computer startup and allows the applications to start more quickly when selected later.
前言 常用组件和工具的quick start
通用 Mapper 1)引入依赖:
1 2 3 4 5 <dependency > <groupId > tk.mybatis</groupId > <artifactId > mapper-spring-boot-starter</artifactId > <version > 版本号</version > </dependency >
2)文件配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #tomcat port server.port=8080 #datasource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot-tkmybatis01?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull spring.datasource.username=root spring.datasource.password=laowang #logging logging.level.com.arsenal.mapper:debug #TkMybatis setting mybatis.mapper-locations=classpath*:mapper/*.xml mybatis.type-aliases-package=com.arsenal.entity #驼峰命名 mybatis.configuration.map-underscore-to-camel-case=true
3) 相关代码:
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 @Data @Table (name="country" )public class Country { @Id private Integer id; private String countryname; private String countrycode; } import org.apache.ibatis.annotations.Select;import tk.mybatis.mapper.common.Mapper;public interface CountryMapper extends Mapper <Country > { @Select ("select * from country where countryname = #{countryname}" ) Country selectByCountryName (String countryname) ; } Example example = new Example(Country.class ) ; example.xxx...; countryMapper.selectByExample(example); @tk .mybatis.spring.annotation.MapperScan(basePackages = "扫描包" )@SpringBootApplication public class Application { public static void main (String[] args) { SpringApplication.run(QuickStartApplication.class , args ) ; } }
MybatisPlus 1)引入依赖:
1 2 3 4 5 <dependency > <groupId > com.baomidou</groupId > <artifactId > mybatis-plus-boot-starter</artifactId > <version > 版本号</version > </dependency >
2)文件配置:
1 2 3 4 5 6 7 # DataSource Config spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot-tkmybatis01?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull username: root password: laowang
3) 相关代码:
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 @Data public class User { private Long id; private String name; private Integer age; private String email; } public interface UserMapper extends BaseMapper <User > {} QueryWrapper<User> queryWrapper = new QueryWrapper<>(); List<User> userList = userMapper.selectList(queryWrapper.lambda().eq(User::getName, id)); @SpringBootApplication @MapperScan ("扫描包" )public class Application { public static void main (String[] args) { SpringApplication.run(QuickStartApplication.class , args ) ; } }
JPA 1)引入依赖:
1 2 3 4 5 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-jpa</artifactId > <version > 版本号</version > </dependency >
2)文件配置:
1 2 3 4 5 6 7 8 9 10 11 12 server.port =8080 spring.datasource.driver-class-name =com.mysql.jdbc.Driver spring.datasource.url =jdbc:mysql://localhost:3306/springboot-tkmybatis01?allowMultiQueries=true&useUnicode=true&useSSL=false&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull spring.datasource.username =root spring.datasource.password =laowang logging.level.com.arsenal.mapper :debug spring.jpa.database =mysql spring.jpa.show-sql =true
3) 相关代码:
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 49 50 51 52 53 54 55 56 57 58 59 60 @Data @Entity @Table (name="User" )public class User { @Id @GeneratedValue private Long id; @Column (nullable = false ) private String name; @Column (nullable = false , unique = true , updatable = false ) @JsonProperty (value = "email" ) private String username; @Column (nullable = false ) @JsonIgnore private String password; @Column (nullable = false ) @JsonIgnore private String salt; @Column (nullable = true ) private Date birthday; @Column (nullable = false ) private String sex; @Column (nullable = true ) @JsonFormat (pattern="yyyy-MM-dd HH:mm:ss" ) private Timestamp access; @Column (nullable = true ) @JsonFormat (pattern="HH:mm:ss" ) private Time accessTime; @Column (nullable = false ) private Integer state; @Column (nullable = false , insertable = false , updatable = false ) @JsonFormat (pattern="yyyy-MM-dd HH:mm:ss" ) private Timestamp created; @Column (nullable = false , insertable = false , updatable = false ) @JsonFormat (pattern="yyyy-MM-dd HH:mm:ss" ) private Timestamp updated; } public interface UserRepository extends JpaRepository <User , Long >, UserCustomRepository { User findByUsername (String username) ; @Transactional @Modifying @Query ("UPDATE User SET state = ?2 WHERE id = ?1 " ) Integer saveState (Long id, Integer state) ; }
RabbitMQ 1)引入依赖:
1 2 3 4 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-amqp</artifactId > </dependency >
2)文件配置:
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 server: port: 8001 servlet: context-path: / spring: application: name: rabbit-producer http: encoding: charset: UTF-8 jackson: date-format: yyyy-MM-dd HH:mm:ss default-property-inclusion: NON_NULL time-zone: GMT+8 rabbitmq: addresses: 192.168 .1 .110 :5672 connection-timeout: 15000 password: 123456 username: admin virtual-host: / listener: order: exchange: durable: true key: arsenal.* name: exchange.topic type: topic simple: acknowledge-mode: manual concurrency: 5 max-concurrency: 10 prefetch: 1
3) 相关代码:
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 @Component public class RabbitReceive { @RabbitListener (bindings = @QueueBinding ( value = @Queue (value = "queue-1" , durable = "true" ), exchange = @Exchange (name = "exchange-1" , durable = "true" , type = "topic" , ignoreDeclarationExceptions = "true" ), key = "springboot.*" ) ) @RabbitHandler public void onMessage (Message message, Channel channel) throws Exception { System.err.println("-----------------------" ); System.err.println("消费消息:" + message.getPayload()); Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG); channel.basicAck(deliveryTag, false ); } } @Component public class RabbitSender { @Autowired private RabbitTemplate rabbitTemplate; final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() { @Override public void confirm (CorrelationData correlationData, boolean ack, String cause) { System.err.println("消息ACK结果:" + ack + ", correlationData: " + correlationData.getId()); } }; public void send (Object message, Map<String, Object> properties) throws Exception { MessageHeaders mhs = new MessageHeaders(properties); Message<?> msg = MessageBuilder.createMessage(message, mhs); rabbitTemplate.setConfirmCallback(confirmCallback); CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString()); MessagePostProcessor mpp = new MessagePostProcessor() { @Override public org.springframework.amqp.core.Message postProcessMessage (org.springframework.amqp.core.Message message) throws AmqpException { System.err.println("---> post to do: " + message); return message; } }; rabbitTemplate.convertAndSend("exchange-1" , "springboot.rabbit" , msg, mpp, correlationData); } } @EnableRabbit @SpringBootApplication public class AmqpApplication { public static void main (String[] args) { SpringApplication.run(AmqpApplication.class , args ) ; } }
RocketMQ 1)引入依赖:
1 2 3 4 5 <dependency > <groupId > org.apache.rocketmq</groupId > <artifactId > rocketmq-client</artifactId > <version > 版本号</version > </dependency >
2)文件配置:
1 2 3 spring: rocketmq: namesrvAddr: 127.0 .0 .1 :9876
3) 相关代码:
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 @Slf 4j@Component public class MQPushConsumer implements MessageListenerConcurrently { @Value ("${spring.rocketmq.namesrvAddr}" ) private String namesrvAddr; private final DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("TestRocketMQPushConsumer" ); @PostConstruct public void start () { try { log.info("MQ:启动消费者" ); consumer.setNamesrvAddr(namesrvAddr); consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); consumer.setMessageModel(MessageModel.CLUSTERING); consumer.subscribe("TopicTest" , "*" ); consumer.registerMessageListener(this ); consumer.start(); } catch (MQClientException e) { log.error("MQ:启动消费者失败:{}-{}" , e.getResponseCode(), e.getErrorMessage()); throw new RuntimeException(e.getMessage(), e); } } @Override public ConsumeConcurrentlyStatus consumeMessage (List<MessageExt> msgs, ConsumeConcurrentlyContext context) { int index = 0 ; try { for (; index < msgs.size(); index++) { MessageExt msg = msgs.get(index); String messageBody = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET); log.info("MQ:消费者接收新信息: {} {} {} {} {}" , msg.getMsgId(), msg.getTopic(), msg.getTags(), msg.getKeys(), messageBody); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (index < msgs.size()) { context.setAckIndex(index + 1 ); } } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } @PreDestroy public void stop () { if (consumer != null ) { consumer.shutdown(); log.error("MQ:关闭消费者" ); } } } @Slf 4j@Component public class MQProducer { @Value ("${spring.rocketmq.namesrvAddr}" ) private String namesrvAddr; private final DefaultMQProducer producer = new DefaultMQProducer("TestRocketMQProducer" ); @PostConstruct public void start () { try { log.info("MQ:启动生产者" ); producer.setNamesrvAddr(namesrvAddr); producer.start(); } catch (MQClientException e) { log.error("MQ:启动生产者失败:{}-{}" , e.getResponseCode(), e.getErrorMessage()); throw new RuntimeException(e.getMessage(), e); } } public void sendMessage (String data, String topic, String tags, String keys) { try { byte [] messageBody = data.getBytes(RemotingHelper.DEFAULT_CHARSET); Message mqMsg = new Message(topic, tags, keys, messageBody); producer.send(mqMsg, new SendCallback() { @Override public void onSuccess (SendResult sendResult) { log.info("MQ: 生产者发送消息 {}" , sendResult); } @Override public void onException (Throwable throwable) { log.error(throwable.getMessage(), throwable); } }); } catch (Exception e) { log.error(e.getMessage(), e); } } @PreDestroy public void stop () { if (producer != null ) { producer.shutdown(); log.info("MQ:关闭生产者" ); } } }
Kafka 1)引入依赖:
2)文件配置:
3) 相关代码:
Cache
>