一、打开user-service微服务
启动类右键Run’UserServiceApplication’或者点击右上方启动
2 Springboot连接Mysql数据库
(1)首先我们将需要的包导入,这几个包都是我们稍后要用到的:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
(2)在application.yml配置你数据库的信息
主要是在spring下添加datasource
server: port: 8201 spring: application: name: user-service datasource: url: jdbc:mysql://localhost:3306/day1?serverTimezone=UTC&useSSL=false username: root password: ****** driver-class-name: com.mysql.cj.jdbc.Driver eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:10086/eureka/
(3)测试是否成功
建立一个controller包,在它下面创建一个TestController类
package com.hztest.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @RestController public class TestController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping("/getUsers") public List<Map<String, Object>> getDbType(){ String sql = "select * from student"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); for (Map<String, Object> map : list) { Set<Map.Entry<String, Object>> entries = map.entrySet( ); if(entries != null) { Iterator<Map.Entry<String, Object>> iterator = entries.iterator( ); while(iterator.hasNext( )) { Map.Entry<String, Object> entry =(Map.Entry<String, Object>) iterator.next( ); Object key = entry.getKey( ); Object value = entry.getValue(); System.out.println(key+":"+value); } } } return list; } }
然后我们在浏览器端输入:
http://localhost:端口号+路径
http://localhost:8201/getUsers