导入 Druid 依赖,代码如下: <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
server.port =8089 server.servlet.context-path=/ spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?serverTimezone=UTC&autoReconnect=true spring.datasource.username=root spring.datasource.password=admin ##spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database=MySQL spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql=true spring.initialSize=5 spring.minIdle=5 spring.maxActive=20 spring.maxWait: 60000 spring.timeBetweenEvictionRunsMillis=60000 spring.minEvictableIdleTimeMillis=300000 spring.validationQuery=SELECT 1 FROM DUAL spring.testWhileIdle=true spring.testOnBorrow=false spring.testOnReturn=false spring.poolPreparedStatements=true spring.filter.stat.enabled=true spring.filter.stat.log-slow-sql=true spring.filter.wall.enabled=true
我们配置 type:com.alibaba.druid.pool.DruidDataSource 来切换数据源,但是文件中数 据源其他配置信息现在还不会启任何作用。 因为 Druid 算是第三方数据源,在 spring boot 中并没有自动配置类,需要自己配置下数 据。所以我们需要自定义一个 Druid 数据源来进行绑定,代码如下:
package com.tszr.jpa.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; @Configuration public class Config { /* 把配置文件中 spring.datasource.initialSize 等属性和 DruidDataSource 中属 性 进行绑定 */ @ConfigurationProperties(prefix = "spring.datasource") @Bean public DruidDataSource druidDataSource() { return new DruidDataSource(); } }
配置 Druid 的监控和过滤器,代码如下:
package com.tszr.jpa.config; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; @Configuration public class DuridConfig { /** * 配置 Druid 的监控 1、配置一个管理后台的 Servlet,拦截登陆 * * @return */ @Bean public ServletRegistrationBean<StatViewServlet> statViewServlet() { ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>( new StatViewServlet(), "/druid/*"); Map<String, String> initParams = new HashMap<>(); initParams.put("loginUsername", "admin"); initParams.put("loginPassword", "123456"); initParams.put("allow", ""); // 允许所有访问 servletRegistrationBean.setInitParameters(initParams); return servletRegistrationBean; } // 配置一个 web 监控的 filter,哪些请求会被监控,哪些排除。 @Bean public FilterRegistrationBean<WebStatFilter> webStatFilter() { FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<WebStatFilter>(new WebStatFilter()); Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
启动项目,当我们访问:http://localhost:8089/druid 就会进入监控的登陆页面
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jdbctemplate</groupId> <artifactId>jdbctemplate</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <!-- 声明项目配置依赖编码格式为 utf-8 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <fastjson.version>1.2.24</fastjson.version> </properties> <dependencies> <!--Spring Data Jpa依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>8.0.13</version><!--$NO-MVN-MAN-VER$ --> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
package com.tszr.jpa.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "t_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "username", unique = true, nullable = false, length = 64) private String username; @Column(name = "password", nullable = false, length = 64) private String password; @Column(name = "email", length = 64) private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.tszr.jpa.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.tszr.jpa.entity.User; public interface UserRepository extends JpaRepository<User, Integer> { /* 相当于select * from t_user where username = ? and password = ? */ public User findByUsernameAndPassword(String username, String password); @Query("select u from User u where u.username like %?1%") public List<User> getUserByUsername(@Param("username") String username); }
package com.tszr.jpa.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.tszr.jpa.entity.User; import com.tszr.jpa.dao.UserRepository; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @PostMapping() // 添加 public User saveUser(@RequestBody User user) { // response.setContentType("application/json;charset=UTF-8"); return userRepository.save(user); } @DeleteMapping("/{id}") // 删除 public void deleteUser(@PathVariable("id") int id) { userRepository.deleteById(id); } @PutMapping("/{id}") public User updateUser(@PathVariable("id") int userId, @RequestBody User user) { user.setId(userId); return userRepository.saveAndFlush(user); } @GetMapping("/{id}") public User getUserInfo(@PathVariable("id") int userId) { Optional<User> optional = userRepository.findById(userId); return optional.orElseGet(User::new); } @GetMapping("/list") public Page<User> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize)); } @GetMapping("/ops") public List<User> getOPs(String username) { return userRepository.getUserByUsername(username); } @PostMapping("/login") public User getPerson(String username, String password) { return userRepository.findByUsernameAndPassword(username, password); } }
package com.tszr.jpa.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { // 1.添加CORS配置信息 CorsConfiguration config = new CorsConfiguration(); // 1) 允许的域,不要写*,否则cookie就无法使用了 config.addAllowedOrigin("http://localhost:8081"); // 2) 是否发送Cookie信息 config.setAllowCredentials(true); // 3) 允许的请求方式 config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); // 4)允许的头信息 config.addAllowedHeader("*"); // 2.添加映射路径,我们拦截一切请求 UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); // 3.返回新的CorsFilter. return new CorsFilter(configSource); } }
package com.tszr.jpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }