在前面博客学习微服务的注册和发现基础下,集成mybatis完成增删查操作自然水到渠成,由三个基础服务就可以完成,分别是服务注册中心,服务提供者,服务消费者。
一、创建服务注册中心(spring-eureka-server)
因为前面博客详细的创建方法,这里不细说了,我直接引用前面博客创建的服务,我使用eureka01(9001) 端口的服务注册中心,并贴上一些关键代码。
pom.xml
spring-cloud
spring-cloud
1.0-SNAPSHOT
4.0.0
spring-eureka-server
0.0.1-SNAPSHOT
UTF-8
UTF-8
1.8
org.springframework.cloud
spring-cloud-starter-eureka-server
org.springframework.cloud
spring-cloud-dependencies
Dalston.SR3
pom
import
org.springframework.boot
spring-boot-maven-plugin
application.properties
spring.application.name=spring-eureka-server
server.port=9001
eureka.instance.hostname=eureka01
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka
二、创建服务提供者(spring-eureka-provide)
(1)先引入springboot集成mybatis、mysql等依赖,pom.xml完整依赖如下
pom.xml
spring-cloud
spring-cloud
1.0-SNAPSHOT
4.0.0
spring-eureka-provide
UTF-8
UTF-8
1.8
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
com.alibaba
druid
1.1.8
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-starter-data-jpa
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-starter-actuator
org.springframework.cloud
spring-cloud-dependencies
Dalston.SR3
pom
import
org.springframework.boot
spring-boot-maven-plugin
application.properties重点:配置数据库连接信息
说明:
(1)spring.application.name设置的名字为服务消费者调用的Url
(2)#db为连接数据库配置信息
(3)info为该端口具体信息
spring.application.name=spring-eureka-provide
server.port=7001
eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/
eureka.instance.instance-id=provide7001
eureka.instance.prefer-ip-address=true
#db
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
info.author.name=zdxh
info.app.name=microservice-provide
info..server.port=${server.port}
info.application.name=${spring.application.name}
(2)创建User实体类,编写controller、service、mapper层逻辑代码
User.java
package eureka.provide.entity;
public class User {
private Integer id;
private String username;
private String password;
}
//省略get、set方法
UserController.java`
说明:
@component (把普通pojo实例化到spring容器中)
package eureka.provide.controller;
import eureka.provide.entity.User;
import eureka.provide.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Component
public class UserController {
@Autowired
Userservice userservice;
@GetMapping("/find/{id}")
public User findByIdUser(@PathVariable("id")Integer id){
User user=userservice.findUser(id);
return user;
}
@GetMapping("/del/{id}")
public String delUser(@PathVariable("id") Integer id) {
int num =userservice.delUser(id);
return num == 1 ? "success" : "error";
}
@GetMapping("/save/{uname}/{pword}")
public String saveUser(@PathVariable("uname") String username, @PathVariable("pword") String password) {
User user=new User();
user.setUsername(username);
user.setPassword(password);
int num=userservice.saveUser(user);
return num == 1? "success": "error";
}
}
UserSerice.java接口
package eureka.provide.service;
import eureka.provide.entity.User;
public interface Userservice {
User findUser(Integer id);
int saveUser(User user);
int delUser(Integer id);
}
UserServiceImpl.java
package eureka.provide.service.impl;
import eureka.provide.entity.User;
import eureka.provide.mapper.UserMapper;
import eureka.provide.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements Userservice {
@Autowired
UserMapper userMapper;
//根据id查询用户
public User findUser(Integer id){
return this.userMapper.findUser(id);
}
//保存用户
public int saveUser(User user){
this.userMapper.saveUser(user);
return 1;
}
//删除用户
public int delUser(Integer id){
this.userMapper.delUser(id);
return 1;
}
}
UserMapper接口
这里引用@Select,@Insert注解方式,所以不需要配置UserMapper.xml文件
package eureka.provide.mapper;
import eureka.provide.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select * from user where id = #{id}")
User findUser(Integer id);
@Insert("insert into user(username,password) values(#{username},#{password})")
void saveUser(User user);
@Select("delete from user where id = #{id}")
void delUser(Integer id);
}
主函数启动类EuerkaProvideApplication
新增@MapperScan注解
@MapperScan:可以指定要扫描的Mapper类的包的路径
package eureka.provide;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
@MapperScan("eureka.provide.mapper")
public class EurekaProvideApplication {
public static void main(String[] args){
SpringApplication.run(EurekaProvideApplication.class,args);
}
}
三、服务消费者(spring-eureka-consume)
pom.xml
(1)新增ribbon负载均衡依赖包
spring-cloud
spring-cloud
1.0-SNAPSHOT
4.0.0
spring-eureka-consume
UTF-8
UTF-8
1.8
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-ribbon
org.springframework.cloud
spring-cloud-dependencies
Dalston.SR3
pom
import
org.springframework.boot
spring-boot-maven-plugin
application.properties
spring.application.name=spring-eureka-consume
server.port=8001
eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/
(2)然后在主函数创建ResTemplate类
package eureka.consume;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableEurekaClient
@SpringBootApplication
public class EurekaConsumeApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args){
SpringApplication.run(EurekaConsumeApplication.class,args);
}
}
(3)最后新建User实体类和和UserController.java
User.java
package eureka.consume.entity;
public class User {
private Integer id;
private String username;
private String password;
}
//省略get、set方法
UserController.java
package eureka.consume.controller;
import eureka.consume.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
@Controller
@Configuration
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/find/{id}")
@ResponseBody
public User find(@PathVariable("id")Integer id){
return restTemplate.getForEntity("http://spring-eureka-provide/find/{id}",User.class,id).getBody();
}
@GetMapping(value = "/del/{id}")
@ResponseBody
public String del(@PathVariable("id") Integer id) {
return restTemplate.getForEntity("http://spring-eureka-provide/del/{id}", String.class,id).getBody();
}
@GetMapping(value = "/save/{username}/{password}")
@ResponseBody
public String save(@PathVariable("username") String username, @PathVariable("password") String password) {
return restTemplate
.getForEntity("http://spring-eureka-provide/save/{username}/{password}", String.class, username, password)
.getBody();
}
}
四、启动各服务测试
(1)先创建数据库springcloud创建user表如下
(2)分别启动各服务,输入localhost:9001,查看各服务是否成功启动
(3)输入localhost:8001/find/1,消费者调用提供者find方法,查询ID=1的用户信息
再测试一下保存用户信息
四、实现负载均衡
再新建一个spring-eureka-provide2,代码配置与provide完成一样,只需要修改端口号。
application.properties
注意:spring.application.name与第一个provide名字要相同
spring.application.name=spring-eureka-provide
server.port=7002
eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/
eureka.instance.instance-id=provide7002
eureka.instance.prefer-ip-address=true
然后分别在两个provide的Controller新建TestController,测试负载均衡。
package eureka.provide.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
public String test(){
return "provide1";
}
}
package eureka.provide.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
public String test(){
return "provide2";
}
}
最后,启动provide2,查看服务
输入localhost:8001/test,测试负载均衡,刷新页面,页面会在provide1和provide2之间跳转
路是一步步走出来的,与大家共勉,有不解之处可评论指出。
`