Spring combines Jboss and Jndi to realize data source external configuration

Spring combines Jboss and Jndi to realize data source external configuration

jndi official description

What is jndi

JNDI (Java Naming and Directory Interface, Java Naming and Directory Interface) is a standard Java naming system interface provided by SUN. JNDI provides a unified client API, through different access provider interfaces JNDI Service Supply Interface (SPI) To achieve the implementation, the manager maps the JNDI API to a specific naming service and directory system, so that Java applications can interact with these naming services and directory services. Directory services are a natural extension of naming services. The key difference between the two is that objects in directory services can have names and attributes (for example, users have email addresses), while objects in naming services have no attributes.

How to create a context using jndi

The JNDI API defines a context that specifies where to find objects. The initial context is usually used as a starting point. In the simplest case, the initial context must be created with the specific implementation and additional parameters required by the implementation. The initial context will be used to look up the name. The initial context is similar to the root or top of the directory tree of a file system.

Implementation Plan One

var contextArgs = new Hashtable<String, String>();

// 设置参数,不同的服务提供商有不同的实现
contextArgs.put( Context.INITIAL_CONTEXT_FACTORY, "com.jndiprovider.TheirContextFactory" );

// 设置url明确数据存储位置
contextArgs.put( Context.PROVIDER_URL, "jndiprovider-database" );

// 此处可以实现安全校验 等

// 创建context
Context myCurrentContext = new InitialContext(contextArgs);
// 在上行下文昭寻找对应的beanName
MyBean myBean = (MyBean)  myCurrentContext.lookup("com.mydomain.MyBean");

Implementation plan two

// 还可以通过添加 jndi 来配置上下文对象。类路径中包含初始上下文工厂类名和提供程序 URL 的属性文件
// 仅需要创建上下文context,将会去类路径下读取配置文件 
Context myCurrentContext = new InitialContext();
// 从上下文中寻找初始化完成的bean信息
MyBean myBean = (MyBean)  myCurrentContext.lookup("com.mydomain.MyBean");

Spring combined with Jboss to achieve jndi injection

Resource manager connection factory references allow application component code to refer to resource factories using logical names called resource manager connection factory references. **The resource manager connection factory reference is defined by the resource ref element in the standard deployment descriptor. **The deployment program uses jboss to bind the resource manager connection factory reference to the actual resource manager connection factory that exists in the target operating environment. **jboss.xml and jboss-web.xml **descriptor

Configure jndi resource data source

In ${jboss_name}/standalone/configuration/standalone.xmlthe configuration

<datasources>
    <!-- jboss 默认的数据库连接配置 -->
    <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
        <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
        <driver>h2</driver>
        <security>
            <user-name>sa</user-name>
            <password>sa</password>
        </security>
    </datasource>
     <!-- mysql 默认的数据库连接配置 -->
    <datasource jndi-name="java:jboss/jdbc/sxsDB" pool-name="mysqlDSPool">
        <connection-url>jdbc:mysql://localhost:3306/testdb</connection-url>
        <driver>mysql</driver>
        <security>
            <user-name>root</user-name>
            <password>123456</password>
        </security>
    </datasource>
    <drivers>
        <!-- mysql 默认的数据库驱动配置 -->
        <driver name="mysql" module="com.mysql">
            <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
        </driver>
         <!-- jboss 默认的数据库驱动配置 -->
        <driver name="h2" module="com.h2database.h2">
            <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
        </driver>
    </drivers>
</datasources>

Configure modules

In ${jboss_name}/modules/system/layers/base/comthe new catalog/mysql/main

Create module.xml in this directory, and add the corresponding version of the mysql driver jar package , as shown in the figure:
1559006898869
module.xml detailed configuration

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mysql">
    <resources>
    <!-- 此处注意与对应jar版本一致 -->
        <resource-root path="mysql-connector-java-5.1.38.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
    </dependencies>
</module>

Configure jboss-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web
        PUBLIC "-//JBoss//DTD Web Application 2.3V2//EN"
        "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">
<jboss-web>
    <context-root>/spring-webmvc-0.0.1-SNAPSHOT</context-root>
    <resource-ref>
        <res-ref-name>jdbc/sxsDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <jndi-name>java:jboss/jdbc/sxsDB</jndi-name>
    </resource-ref>
</jboss-web>

Configure web.xml

<web-app>
    <!-- JDBC DataSources (java:comp/env/jdbc) -->
    <resource-ref>
        <description>The default DS</description>
        <res-ref-name>jdbc/sxsDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

</web-app>

Configure maven related dependencies

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
    
    <!--Spring java数据库访问包,在本例中主要用于提供数据源 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--mysql数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    <!-- mybatis ORM框架 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
    </dependency>
    
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.30</version>
    </dependency>
    <!-- druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.6</version>
    </dependency>

Configure database connection

/**
 * @ClassName: MybatisConfiguration
 * @Description: java类作用描述
 * @Author: 尚先生
 * @CreateDate: 2019/5/24 16:56
 * @Version: 1.0
 */
@Configuration
@MapperScan("com.sxs.web.mapper")
public class MybatisConfiguration {
    
    
    @Bean
    public DataSource dataSource() throws ClassNotFoundException, NamingException {
    
    
//        方式一  Tomcat 实现方式
//        Context initContext = new InitialContext();
//        Context envContext  = (Context)initContext.lookup("java:/comp/env");
//        DataSource dataSource = (DataSource)envContext.lookup("jdbc/sxsDB");

//        方式一 Jboss 实现方式
//        Context initContext = new InitialContext();
//        DataSource dataSource = (DataSource)initContext.lookup("java:jboss/jdbc/sxsDB");

//        方式二 Tomcat 实现方式
        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
        JndiTemplate jndiTemplate = factoryBean.getJndiTemplate();
        DataSource dataSource = jndiTemplate.lookup("java:/comp/env/jdbc/sxsDB", DataSource.class);

//      方式二 Jboss 实现方式
//        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
//        JndiTemplate jndiTemplate = factoryBean.getJndiTemplate();
//        DataSource dataSource = jndiTemplate.lookup("java:jboss/jdbc/sxsDB", DataSource.class);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
    
    
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.sxs.web.model");
        //   "classpath*:sqlmap/*-mapper.xml"
        sqlSessionFactoryBean.setMapperLocations(new Resource[]{
    
    });
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    
    
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

Configure the mapping entity

public class Course implements Serializable {
    
    

    private static final long serialVersionUID = 1848918888438459623L;
    private String course_name;
    private String stu_name;
    private double score;
    private String currentThreadName;

    @Override
    public String toString() {
    
    
        return "Course{" +
                "course_name='" + course_name + '\'' +
                ", stu_name='" + stu_name + '\'' +
                ", score=" + score +
                ", currentThreadName='" + currentThreadName + '\'' +
                '}';
    }

    public String getCourse_name() {
    
    
        return course_name;
    }

    public void setCourse_name(String course_name) {
    
    
        this.course_name = course_name;
    }

    public String getStu_name() {
    
    
        return stu_name;
    }

    public void setStu_name(String stu_name) {
    
    
        this.stu_name = stu_name;
    }

    public double getScore() {
    
    
        return score;
    }

    public void setScore(double score) {
    
    
        this.score = score;
    }

    public String getCurrentThreadName() {
    
    
        return currentThreadName;
    }

    public void setCurrentThreadName(String currentThreadName) {
    
    
        this.currentThreadName = currentThreadName;
    }
}

Configure mapper mapping

@Mapper
@Repository
public interface CourseMapper {
    
    

    @Select("select * from tb_score limit 2 offset 1")
    Collection<Course> findAllCourses();

    @Select("select * from tb_score limit 1 offset 1")
    Course findSingleCourse();
}

Configure the controller

/**
 * @ClassName: CourseController
 * @Description: Course数据测试
 * @Author: 尚先生
 * @CreateDate: 2019/5/22 17:29
 * @Version: 1.0
 */
@RestController
public class CourseController {
    
    

    @Autowired
    private CourseMapper courseMapper;

    // 配置浏览器响应数据编码格式
    @GetMapping(value = "/find-all-courses",produces = {
    
    "application/json;charset=UTF-8"})
    public Collection<Course> findAllCourses(){
    
    

        Collection<Course> courses1 = courseMapper.findAllCourses();

        for (Course course : courses1){
    
    
            course.setCurrentThreadName(Thread.currentThread().getName());
        }
        return courses1;
    }

    @GetMapping(value = "/find-single-course",produces = {
    
    "application/json;charset=UTF-8"})// 配置浏览器响应数据编码格式
    public String findSingleCourse(){
    
    
        Course course = courseMapper.findSingleCourse();
        course.setCurrentThreadName(Thread.currentThread().getName());
        return JSON.toJSONString(course);
    }
}

Add SQL script

-- 查询所有的数据库
show databases;
-- 使用testdb
use testdb;
-- 查询testdb所有的表
show tables ;
-- 建表前清除
drop table tb_score;
-- 建表语句
create table tb_score(
  id bigint primary key auto_increment,
  course_name varchar(20),
  stu_name varchar(20),
  score double
);
-- 插入数据
insert into tb_score (course_name, stu_name, score) values ('高数','尚先生',100.00);
insert into tb_score (course_name, stu_name, score) values ('英语','尚先生',80.00);
insert into tb_score (course_name, stu_name, score) values ('英语','尚小菲',100.00);
insert into tb_score (course_name, stu_name, score) values ('高数','尚小菲',90.00);
-- 查询入库数据
select *
from tb_score;

Reference article

http://www.informit.com/articles/printerfriendly/28281

More excellent articles

Elementary school students in java
https://blog.csdn.net/shang_xs

More Tomcat related

Spring combines Tomcat and Jndi to realize data source external configuration

https://blog.csdn.net/shang_xs/article/details/90599810

In-depth study and understanding of Servlet (1)
https://blog.csdn.net/shang_xs/article/details/90371068 In-
depth study and understanding of Servlet (2)
https://blog.csdn.net/shang_xs/article/details/90376489

Please see GitHub for the complete code and related dependencies

https://github.com/dwyanewede/spring-boot/tree/master/spring-webmvc/src/main

Official account recommendation

Insert picture description here

Guess you like

Origin blog.csdn.net/shang_xs/article/details/90610242