Knife4j

Knife4j是Java MVC框架集成Swagger生成Api文档的增强解决方案

使用方法:1.导入knife4j的maven坐标

​ 2.在配置类中加入knife4j相关配置

​ 3.设置静态资源映射,否则接口文档页面无法访问

1
2
3
4
5
<dependency>
<groupId>com.gitthub.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>

在config包下的WebMvcConfiguration的配置

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
package com.sky.config;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
* 配置类,注册web层相关组件
*/
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

@Autowired
private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;

/**
* 注册自定义拦截器
*
* @param registry
*/
protected void addInterceptors(InterceptorRegistry registry) {
log.info("开始注册自定义拦截器...");
registry.addInterceptor(jwtTokenAdminInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/employee/login");
}

/**
* 通过knife4j生成接口文档
* @return
*/
@Bean
public Docket docket() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("苍穹外卖项目接口文档")
.version("2.0")
.description("苍穹外卖项目接口文档")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sky.controller")) //要扫描的包
.paths(PathSelectors.any())
.build();
return docket;
}

/**
* 设置静态资源映射
* @param registry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}



Swagger常用注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Api                    //用在类上,例如Controller,表示对类的说明
@ApiOperation //用在方法上,例如Controller的方法,说明方法的用途、作用
@ApiModel //用在类上,例如entity,DTO,VO
@ApiModelProperty //用在属性上,描述属性信息

//示例
@ApiModel(description = "员工登录时传递的数据模型")
public class EmployeeLoginDTO implements Serializable {
@ApiModelProperty("用户名")
private String username;

@ApiModelProperty("密码")
private String password;

}
1
2
3
//对象属性拷贝
Employee employee = new Employee();
BeanUtils.copyProperties(employeeDTO, employee); // (原数据,拷贝后的新数据)

Redis

pom文件引入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

config包下创建 RedisConfiguration

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
log.info("开始创建RedisTemplate对象...");
RedisTemplate redisTemplate = new RedisTemplate();
// 设置RedisConnectionFactory
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 设置key的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}

使用

1
2
3
4
@Autowired
private RedisTemplate redisTemplate;
redisTemplate.opsForValue().set("SHOP_STATUS", status);
Integer status = (Integer) redisTemplate.opsForValue().get("SHOP_STATUS");

HttpClient

1
2
3
4
5
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>

发送请求步骤

1.创建 HttpClient对象

2.创建Http请求对象

3.调用HttpClient的execute方法发送请求

1
2
3
4
5
6
7
8
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://jin88.top/xianyuepro/random"); //发送GET请求
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
System.out.println(body+"body");
response.close(); //关闭响应
httpClient.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
      CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://jin88.top/xianyuepro/index/login");

JSONObject jsonObject =new JSONObject();
jsonObject.put("phone", "17356288857");
jsonObject.put("pwd", "123456");

StringEntity stringEntity = new StringEntity(jsonObject.toJSONString());
// stringEntity.setContentEncoding("utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);

CloseableHttpResponse execute = httpClient.execute(httpPost); //发送POST请求
HttpEntity entity = execute.getEntity();
String body = EntityUtils.toString(entity);
System.out.println(body+"body");
execute.close();
httpClient.close();

Spring Cache

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.7.3</version>
</dependency>
1
2
3
4
5
6
7
8
@SpringBootApplication  //用在启动类上
@EnableTransactionManagement //开启注解方式的事务管理 用在启动类上
@EnableCaching //开启缓存功能 ************************用在启动类上

@Cacheable(cacheNames = "setmealCache", key = "#categoryId") // key = "#categoryId" // 有缓存返回缓存,没有则查询后将结果存入缓存并返回
@CachePut // 将方法的返回值放到缓存中
@CacheEvict(cacheNames = "setmealCache",allEntries = true) //将一条或多条数据从缓存中删除
@CacheEvict(cacheNames = "setmealCache",key = "#setmealDTO.categoryId")//key: setmealCache::100

Spring Task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//导入maven坐标 spring-context (已存在)
@EnableScheduling //开启定时任务功能
//建立Task类 需要添加 @Component
@Component
@Slf4j
public class MyTask {
@Scheduled(cron = "0/5 * * * * ?") //定时任务 每隔5秒触发一次
public void executeTask(){
log.info("定时任务开始执行:{}", new Date());
}

}

//时间加减 plusMinutes(-15)
LocalDateTime time = LocalDateTime.now().plusMinutes(-15); // -15表示15分钟之前
LocalDateTime.now().plusMinutes(15); //15分钟之后

WebScoket

websocket包下

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
package com.sky.websocket;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component //WebSocket服务
@ServerEndpoint("/ws/{sid}") //参数
public class WebSocketServer {
private static Map<String, Session> sessionMap = new HashMap(); //存放会话对象

@OnOpen //连接建立成功调用的方法
public void onOpen(Session session, @PathParam("sid") String sid) {
System.out.println("客户端:" + sid + "建立连接");
sessionMap.put(sid, session);
}


@OnMessage //收到客户端消息后调用的方法
public void onMessage(String message, @PathParam("sid") String sid) {
System.out.println("收到来自客户端:" + sid + "的信息:" + message);
}

@OnClose //连接关闭调用的方法
public void onClose(@PathParam("sid") String sid) {
System.out.println("连接断开:" + sid);
sessionMap.remove(sid);
}

public void sendToAllClient(String message) { //群发
Collection<Session> sessions = sessionMap.values();
for (Session session : sessions) {
try { //服务器向客户端发送消息
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 //  WebSocket配置类,用于注册WebSocket的Bean config包下
package com.sky.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
* WebSocket配置类,用于注册WebSocket的Bean
*/
@Configuration
public class WebSocketConfiguration {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

}