Quick Start

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;
}

//mapper
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;
}

//mapper
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
#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
#jpa setting
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;
}


//JpaRepository
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
# 使用启用消息确认模式
#publisher-confirms: true
username: admin
virtual-host: /
listener:
# 最好不要在代码里写死配置信息,尽量使用这种方式也就是配置文件的方式
# 在代码里使用 ${} 方式进行设置配置: ${spring.rabbitmq.listener.order.exchange.name}
order:
exchange:
durable: true
key: arsenal.*
name: exchange.topic
type: topic
# 表示消费者消费成功消息以后需要手工的进行签收(ack),默认为auto
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 @QueueBinding @Queue @Exchange
* @param message
* @param channel
* @throws Exception
*/
@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 {
// 1. 收到消息以后进行业务端消费处理
System.err.println("-----------------------");
System.err.println("消费消息:" + message.getPayload());

// 2. 处理成功之后 获取deliveryTag 并进行手工的ACK操作, 因为我们配置文件里配置的是 手工签收
// spring.rabbitmq.listener.simple.acknowledge-mode=manual
Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
channel.basicAck(deliveryTag, false);
}

}


@Component
public class RabbitSender {

@Autowired
private RabbitTemplate rabbitTemplate;

/**
* 这里就是确认消息的回调监听接口,用于确认消息是否被broker所收到
*/
final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
/**
* @param ack broker 是否落盘成功
* @param cause 失败的一些异常信息
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.err.println("消息ACK结果:" + ack + ", correlationData: " + correlationData.getId());
}
};

/**
* 对外发送消息的方法
* @param message 具体的消息内容
* @param properties 额外的附加属性
* @throws Exception
*/
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);

// 指定业务唯一的iD
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
@Slf4j
@Component
public class MQPushConsumer implements MessageListenerConcurrently {

@Value("${spring.rocketmq.namesrvAddr}")
private String namesrvAddr;

private final DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("TestRocketMQPushConsumer");

/**
* 初始化
* @throws MQClientException
*/
@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);
}

}

/**
* 消费消息
* @param msgs
* @param context
* @return
*/
@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:关闭消费者");
}
}

}



@Slf4j
@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);
}
}

/**
* 发送消息
* @param data 消息内容
* @param topic 主题
* @param tags 标签
* @param keys 唯一主键
*/
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)引入依赖:

1
2


2)文件配置:

1
2


3) 相关代码:

1
2


Content
  1. 1. 前言
  2. 2. 通用 Mapper
  3. 3. MybatisPlus
  4. 4. JPA
  5. 5. RabbitMQ
  6. 6. RocketMQ
  7. 7. Kafka