文章目录
SpringBoot
- 使用Spring Initializr创建工程,勾选Spring Web
- 导入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
- application.properties配置文件改为application.yml
- 配置端口:
server:
port: 8080
Json序列化
Jackson
- 创建JacksonObjectMapper类并继承ObjectMapper
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/**
* 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象
* 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
* 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
*/
public class JacksonObjectMapper extends ObjectMapper {
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public JacksonObjectMapper() {
super();
//收到未知属性时不报异常
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时,属性不存在的兼容处理
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(BigInteger.class, ToStringSerializer.instance)
.addSerializer(Long.class, ToStringSerializer.instance)
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//注册功能模块 例如,可以添加自定义序列化器和反序列化器
this.registerModule(simpleModule);
}
}
- 创建config类并继承WebMvcConfigurationSupport
在其中重写扩展消息转换器的方法,将新建的JacksonObjectMapper设为消息转换器
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* 扩展spring mvc的消息转换器
* @param converters
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("扩展消息转换器……");
//创建消息转换器对象
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
//设置对象转换器,底层使用Jackson将java对象转为json
messageConverter.setObjectMapper(new JacksonObjectMapper());
//将上面的消息转换器对象追加到mvc的转换器集合中
converters.add(0,messageConverter);
}
}
- 将json转为java对象
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);
- 将java对象转为json
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(myObject);
fastjson
- 引入依赖
<!--fastjson依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
- 新建config类添加配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean//使用@Bean注入fastJsonHttpMessageConvert
public HttpMessageConverter fastJsonHttpMessageConverters() {
//1.需要定义一个Convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
SerializeConfig.globalInstance.put(Long.class, ToStringSerializer.instance);
fastJsonConfig.setSerializeConfig(SerializeConfig.globalInstance);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(fastJsonHttpMessageConverters());
}
}
- 将json转为java对象
MyObject myObject = JSON.parseObject(jsonString, MyObject.class);
- 将java对象转为json字符串
String jsonString = JSON.toJSONString(myObject);
Mybatis-Plus
- 导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
- 编写配置文件application.yml
#下面这些内容是为了让MyBatis映射
mybatis:
#指定Mybatis的Mapper文件
mapper-locations=classpath: mappers/*xml
#指定Mybatis的实体目录
type-aliases-package: com.rainbow.entity
mybatis-plus:
configuration:
#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射.
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id type: ASSIGN_ID
- 配置mapper、service、serviceImpl
- mapper:创建接口继承BaseMapper;该接口用@Mapper注解
- service:创建接口继承IService
- serviceImpl:创建类实现service接口;继承ServiceImpl;用@Service注解该类
Mysql
- 导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
- 配置文件application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/DatabaseName
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
Nginx
- 启动nginx
- 编写配置文件
nginx.conf
# 定义后端服务器组,Nginx在这些服务器中分配请求负载
upstream ServerGroupName{
# 定义服务器的地址
server localhost:51601;
}
server {
# nginx端口
listen 8801;
location / {
root D:/workspace/app-web/ ;
index index.html;
}
location ~/app/(.*) {
proxy_pass http://app-gateway/$1; #将请求中的app及之后的部分放到$1的位置
proxy_set_header HOST $host; #不改变源请求头的值
proxy_pass_request_body on; #开启获取请求体
proxy_pass_request_headers on; #开启获取请求头
proxy_set_header X-Real-IP $remote_addr; # 记录真实发出请求的客户端IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #记录代理信息
}
或是在nginx.conf
中引入其他.conf
文件
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#引入自定义配置文件
include ConfPackage/*.conf;
}
注意:修改完配置文件后需要使用
nginx -s reload
重新加载启动nginx
Redis
- 需要在服务器上启动Redis服务
- 在Java中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--common-pool对象池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
- 配置文件application.yml中配置redis
spring:
redis:
host: 192.168.133.128
port: 6379
password: root
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 100ms
- 注入RedisTemplate
@Autowired
private RedisTemplate redisTemplate
Nacos
- 服务器启动Nacos
- java导入依赖
- 父工程引入Alibaba的SpringCloud依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
- 客户端引入nacos-discovery依赖
<!-- nacos客户端依赖包 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- 在配置文件application.yml中配置nacos
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yml
Feign
- 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 在服务消费者的启动类上添加注解
@EnableFeignClients
开启Feign的功能 - 在服务消费者的包下定义接口,加上服务提供者的接口
- 使用该接口实现远程调用
网关Gateway
- 引入依赖
<!--网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
- 编写基本配置
server:
port: 10010 # 网关端口
spring:
application:
name: gateway # 服务名称
cloud:
nacos:
server-addr: localhost:8848 # nacos地址
gateway:
globalcors:
cors-configurations :
'[/**]': #匹配所有请求
allowedOrigins: "*" #跨域处理允许所有的域
allowedMethods: #支持的方法
- GET
- POST
- PUT
- DELETE
routes: # 网关路由配置
- id: user-service # 路由id,自定义,只要唯一即可
# uri: http://127.0.0.1:8081 # 路由的目标地址 http就是固定地址
uri: lb://userservice # 路由的目标地址 lb就是负载均衡,后面跟服务名称
predicates: # 路由断言,也就是判断请求是否符合路由规则的条件
- Path=/user/** # 这个是按照路径匹配,只要以/user/开头就符合要求
filters:
- StripPrefix = 1 # 转发请求到达目标路径时去除一级路径,例:api/user/service转发后变为user/service(但该过滤器不能随便使用,以免转发后不能正常调用服务)
RabbitMQ
- 服务器启动RabbitMQ
- 引入依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 配置
spring:
rabbitmq:
host: 192.168.133.128 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: root # 用户名
password: root # 密码
- 注入
RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate
- 服务提供者
rabbitTemplate.convertAndSend
- 服务提供者
@RabbitListener
Kafka
- 拉取镜像
docker pull zookeeper:3.4.14
- 创建容器
docker run -d --name zookeeper -p 2181:2181 zookeeper:3.4.14
- 导入依赖
<!-- kafkfa -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
</dependency>
- 配置文件
server:
port: 9991
spring:
application:
name: kafka-demo
kafka:
bootstrap-servers: 192.168.133.128:9092 #kafka地址
producer:
retries: 10 #重试次数
key-serializer: org.apache.kafka.common.serialization.stringSerializer
value-serializer: org.apache.kafka.common.serialization.stringSerializer
consumer:
group-id: test-hello-group #组名称
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.stringDeserializer
- 注入
KafkaTemplate
- 生产者调用
send(String topic,String message)
- 消费者使用注解
@KafkaListener(topics = "xxx")
,方法上用String message
作参数接收消息
Elasticsearch
- 导入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
- 初始化代码
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.133.128:9200")
));