Spring Cloud 第七篇:spring cloud 整合 配置文件以及 mybatis

时间:2024-03-24 07:22:56

在上几篇 项目的基础上来修改服务代码。

首先修改,service-hi 项目(服务提供方),pom.xml文件如下

 

<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
	<artifactId>EurekaClient1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>eurekaClient1</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>com.example</groupId>
		<artifactId>eureka</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>


	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- SpringCloud实现的eureka服务注册于发布器 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</dependency>
		<!-- SpringCloud配置启动器 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<!-- 与数据库操作相关的依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!-- 使用数据源 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.14</version>
		</dependency>

		<!-- mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 开源分页插件地址:http://git.oschina.net/free/Mybatis_PageHelper -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.0.4</version>
		</dependency>
		<dependency>
			<groupId>com.github.jsqlparser</groupId>
			<artifactId>jsqlparser</artifactId>
			<version>0.9.5</version>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Dalston.SR1</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>


	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

创建MybatisConfig 类:数据库的url 用户名,密码是从远程config-server 服务获取的,在MyDbProperties.class 中

package com.example.demo;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

/**
 *
 * @author biguan
 * @create 2018/10/29
 */
@Component
@Configuration
@EnableConfigurationProperties(value = MyDbProperties.class)
@MapperScan(basePackages = {"com.example.demo.mapper"})
public class MyBatisConfig {

    @Autowired
    MyDbProperties myDbProperties;

    @Bean
    public PlatformTransactionManager DataTransaction(@Qualifier("localhostDataSource") DataSource localhostDataSource) {
        return new DataSourceTransactionManager(localhostDataSource);
    }

    @Bean(destroyMethod = "close")
    @ConditionalOnMissingBean(name = "localhostDataSource")
    public DataSource localhostDataSource() {
        Properties props = new Properties();
        props.put("driverClass", "com.mysql.jdbc.Driver");
        props.put("url", myDbProperties.getUrl());
        props.put("username", myDbProperties.getUsername());
        props.put("password", myDbProperties.getPassword());
        try {
            return DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean(name ={"localhostSqlSessionFactory"})
    public SqlSessionFactory localhostSqlSessionFactory(@Qualifier("localhostDataSource") DataSource localhostDataSource)
            throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(localhostDataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactory.setConfigLocation(resolver.getResource("classpath:mybatis/config/supportingConfig.xml"));
        sqlSessionFactory.setMapperLocations(resolver.getResources("classpath:mybatis/localhost/*.xml"));
        return sqlSessionFactory.getObject();
    }
}

创建MyDbProperties.class 来映射 配置文件里面的参数

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author biguan
 * @create 2018/10/26
 */
@ConfigurationProperties(prefix = "localhost.db")
@Configuration
public class MyDbProperties {

    private String url;

    private String username;

    private String password;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    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;
    }
}

创建controller,UserController.class

package com.example.demo.controller;

import com.example.demo.MyDbProperties;
import com.example.demo.mapper.ExpressMapper;
import com.example.demo.model.ExpressBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *
 * @author biguan
 * @create 2018/10/29
 */
@RestController
@EnableConfigurationProperties(value = MyDbProperties.class)
public class UserController {

    @Value("${server.port}")
    public String port;

    @Value("${app.hello}")
    private String hello;

    @Autowired
    private ExpressMapper expressMapper;

    @Autowired
    MyDbProperties myDbProperties;

    @RequestMapping("/hi")
    public String home(@RequestParam String name) {
        List<ExpressBean> ss = expressMapper.queryExpress();
        return "hi " + name + ",i am from" + hello + " ,port:" + port + "\n \r" + "我的数据库连接,用户名,密码分别是:" + myDbProperties.getUrl() + "|" + myDbProperties.getUsername() + "|" + myDbProperties.getPassword()+ "\r\n  "+ss.toString();
    }

    @RequestMapping("/query")
    public List<ExpressBean> query() {
        System.out.println("i am from" + hello + " ,port:" + port + "\n \r" + "我的数据库连接,用户名,密码分别是:" + myDbProperties.getUrl() + "|" + myDbProperties.getUsername() + "|" + myDbProperties.getPassword());
        return expressMapper.queryExpress();
    }
}

创建Mapper:ExpressMapper.class:

package com.example.demo.mapper;

import com.example.demo.model.ExpressBean;

import java.util.List;

/**
 * @author biguan
 * @create 2018/10/29
 */
public interface ExpressMapper {

    List<ExpressBean> queryExpress();
}

创建 bean :ExpressBean:

package com.example.demo.model;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

/**
 * @author biguan
 * @create 2018/10/29
 */
public class ExpressBean {

    private String id;

    private String nick_name;

    private String item_name;

    private String mobile;

    private String order_id;

    private String express_order;

    private String express_company;

    private String address;

    private String activity_code;

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date updateTime;
}

启动类:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient
@SpringBootApplication
@EnableAutoConfiguration
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}


}

然后添加Mapp.xml :ExpressMapper.xml 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.mapper.ExpressMapper">


    <select id="queryExpress" resultType="com.example.demo.model.ExpressBean">
		SELECT * FROM express_info
	</select>

</mapper>

至此服务提供方修改结束,接下来修改客户端feign:

在server-feign 端 修改 controller 添加  query 查询方法调用

package com.example.demo;

import com.example.demo.model.ExpressBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 *
 * @author biguan
 * @create 2018/10/18
 */
@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @RequestMapping(value = "/hi")
    public String sayHelloPort(@RequestParam String name){
        return helloService.sayHelloPort(name);
    }

    @RequestMapping(value = "/query")
    public List<ExpressBean> query(){
        return helloService.query();
    }
}

service:

package com.example.demo;

import com.example.demo.model.ExpressBean;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 *
 * @author biguan
 * @create 2018/10/18
 */
@FeignClient(value = "service-hi",fallback = HelloServiceImpl.class)
public interface HelloService {

    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHelloPort(@RequestParam("name") String name);

    @RequestMapping(value = "/query",method = RequestMethod.GET)
    List<ExpressBean> query();

}

修改结束。

修改配置中心项目   config-server

远程 git 文件 添加Spring Cloud 第七篇:spring cloud 整合 配置文件以及 mybatis

分别启动 注册中心,服务提供方  server-hi,   服务调用方:server-feign,远程配置中心:config-server。

注册中心:

Spring Cloud 第七篇:spring cloud 整合 配置文件以及 mybatis

浏览器输入:http://localhost:8765/query

Spring Cloud 第七篇:spring cloud 整合 配置文件以及 mybatis

查看控制台输出:

Spring Cloud 第七篇:spring cloud 整合 配置文件以及 mybatis

 

以上。