【JavaWeb+ShardingJDBC+Maven+Redis】避坑指南

文章目录

    • jar包下载
    • jar包依赖缺失&冲突
    • 配置maven的pom.xml
    • pom.xml中依赖标红
    • maven在哪设置本地仓库和中央仓库的位置
    • 下载依赖包速度太慢,如何换源
    • properties默认路径
    • 自定义资源文件properties的路径
    • Util工具类编写
    • sharding-jdbc3.0.0和sharding-jdbc4.0.0的区别
    • JdbcTemplate还能用吗?
    • {pageContext.request.contextPath}被错误解析为%7...%7
    • 模糊查询(like)动态语句
    • Redis的maven引用
    • Redis连接失败
    • Redis客户端被拒绝/Redis服务端黑框闪退

 
 

jar包下载

还在为找不到jar包烦恼吗?这里提供几个好用的站点:

maven中央仓库:https://mvnrepository.com(全,速度堪忧)

Kumapai派:https://www.kumapai.com/open(不是很全,国内源)

jar包盒子:https://www.findjar.com(国外源,优点是把所找jar包的Dependencies依赖也标的很详细)

 

jar包依赖缺失&冲突

编译成功,运行失败。报依赖缺失,DataSource集合数据源生成失败。

原因在于:手动向lib导入一个sharding-jdbc-core是不够的——其中的依赖关系非常复杂

此时手动导jar包会进入死胡同,越导入缺失越多冲突越多,只能求助于maven——接着向下看

 

配置maven的pom.xml

<dependencies>

	
	

 	
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.21version>
    dependency>

    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.0.9version>
    dependency>

    
    <dependency>
      <groupId>io.shardingspheregroupId>
      <artifactId>sharding-jdbc-coreartifactId>
      <version>3.0.0version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.3.0version>
    dependency>

	    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.0.1version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.1version>
      <scope>providedscope>
    dependency>

      
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.3.0version>
    dependency>

    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-nopartifactId>
      <version>1.7.30version>
    dependency>

    
    <dependency>
      <groupId>commons-logginggroupId>
      <artifactId>commons-loggingartifactId>
      <version>1.2version>
    dependency>
    
dependencies>

 

pom.xml中依赖标红

解决99%的问题:

  • 自动从私服或中央仓库下载jar包(本地仓库就很快),需要一点时间,耐心等一下下~
  • 手动点一下reimport,耐心等一下下~
  • 玄学1:先删除标红依赖 —> reimport —> 重新加上刚才的依赖 —> reimport
  • 玄学2:从本地仓库删除原有依赖,然后reimport重新下载

终极解决方法:

  1. mvn dependency:purge-local-repository强制清理并重新下载pom.xml中的全部依赖jar
  2. 注释掉pom.xml中的标红依赖
  3. mvn clean
  4. 去掉刚刚的注释
  5. reimport

 

maven在哪设置本地仓库和中央仓库的位置

中文:文件----设置----构建,执行,部署----构建工具----Maven

英文:File—Settings----Build,Execution,Deployment----Build Tools----Maven

 
 

下载依赖包速度太慢,如何换源

你的maven安装目录/conf/setting.xml中添加国内镜像(阿里):

<mirrors>
	<mirror>
		<id>alimavenid>
		<name>aliyun mavenname>
		<url>http://maven.aliyun.com/nexus/content/groups/public/url>
		<mirrorOf>centralmirrorOf>
	mirror>
mirrors>

 
 

properties默认路径

properties空指针报错的问题 java.lang.NullPointerException的原因大概率是未能读取到相应的properties文件

maven读取资源文件的默认路径为:src/main/resources

也就是说,往往需要我们在main下(与java并列)新建一个resources资源目录

 

自定义资源文件properties的路径

我们也可以自定义默认路径——在pom.xml中添加:


<resources>
	<resource>
		<directory>src/main/javadirectory>
		<includes>
			<include>druid.propertiesinclude>
		includes>
	resource>
resources>

 
 

Util工具类编写

JDBCUtils工具类一般只连接一个数据库(数据源),因此适合使用properties配置文件

ShardingJDBCUtils工具类需要连接到多个数据库(数据源),还是老老实实直接把字符串当参数写吧 >_<

  1. 获取普通数据源集合
  2. 表配置(逻辑,真实)
  3. 分片策略(库分片策略/表分片策略)
  4. 分片规则配置(上面的分片策略传进去就行)
public class ShardingJDBCUtils {

    /**
     * 构建(普通)数据源
     * @param url
     * @param username
     * @param password
     * @return
     */
    public static DataSource createDataSource(String url, String username, String password){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(Driver.class.getName());
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }


    /**
     * 构建分片(Sharding)数据源
     */
    public static DataSource getShardingDataSource() throws SQLException {
        // (普通)数据源集合
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("ds_0", createDataSource("jdbc:mysql://localhost:3306/ds_0?serverTimezone=GMT%2B8", "root", "20006212000d"));
        dataSourceMap.put("ds_1", createDataSource("jdbc:mysql://localhost:3306/ds_1?serverTimezone=GMT%2B8", "root", "20006212000d"));

        // 表配置
        TableRuleConfiguration orderTableRuleConfiguration = new TableRuleConfiguration();
        orderTableRuleConfiguration.setLogicTable("order");                             // 逻辑
        orderTableRuleConfiguration.setActualDataNodes("ds_${0..1}.order_${0..1}");     // 真实
        orderTableRuleConfiguration.setKeyGeneratorColumnName("order_id");              // 主键

        // 表的分片策略————order_id % 2
        orderTableRuleConfiguration.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "order_${order_id%2}"));
        // 库的分片策略————user_id % 2
        orderTableRuleConfiguration.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds_${user_id%2}"));

        // 分片规则配置(上面的分片策略传进去就行)
        ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
        shardingRuleConfiguration.getTableRuleConfigs().add(orderTableRuleConfiguration);


        DataSource ds = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new HashMap<String, Object>(), new Properties());
        return ds;
    }

}

 
 

sharding-jdbc3.0.0和sharding-jdbc4.0.0的区别

sharding-sphere官方文档入口:戳这里>_<

但官方文档不是很全,写代码基本靠IDEA提示补全…

配置表规则

// 3.0.0
TableRuleConfiguration orderTableRuleConfiguration = new TableRuleConfiguration();
orderTableRuleConfiguration.setLogicTable("order");                             // 逻辑
orderTableRuleConfiguration.setActualDataNodes("ds_${0..1}.order_${0..1}");     // 真实
orderTableRuleConfiguration.setKeyGeneratorColumnName("order_id");              // 主键
// 4.0.0
TableRuleConfiguration orderTableRuleConfiguration = new TableRuleConfiguration("order","ds_${0..1}.order_${0..1}");

orderTableRuleConfiguration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("String", "order_id"));

生成数据源集合

// 3.0.0
DataSource ds = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new HashMap<String, Object>(), new Properties());
// 4.0.0
DataSource ds = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new Properties());

 
 

JdbcTemplate还能用吗?

可以。完全可以将ShardingJDBC数据源看成普通的JDBC数据源。

JdbcTemplate template = new JdbcTemplate(ShardingJDBCUtils.getShardingDataSource());

 
 

{pageContext.request.contextPath}被错误解析为%7…%7

Java项目中,当你在jsp中使用${pageContext.request.contextPath}来获取相对路径,

访问页面时,${pageContext.request.contextPath}被解析成%7BpageContext.request.contextPath%7D

这是因为maven默认webapp版本号为2.3(打开web.xml即可查看),改为2.4+,最好是4.0即可

 
 

模糊查询(like)动态语句

使用JdbcTemplate,sql字符串中可以使用?进行占位,十分方便。但是使用模糊查询时有个小坑:

String sql = "select * from students where name like '%?%'"		// 错误写法(?在单引号内导致无法解析)

 
 

Redis的maven引用


<dependency>
      <groupId>redis.clientsgroupId>
      <artifactId>jedisartifactId>
      <version>版本任意version>
dependency>

 
 

Redis连接失败

一定要注意,即使我们已经正确引入jar包,Redis仍需要手动开启服务——还自己去找文件夹>_<

 
 

Redis客户端被拒绝/Redis服务端黑框闪退

Redis客户端(redis-cli.exe)异常——我们要开启Redis服务端

Redis服务端(redis-server.exe)黑框闪退——内存分配问题,可以在cmd中限制内存:

(先cd到redis目录下:)

redis-server redis.windows.conf --maxmemory 200m

 
 
 
 

 
 
 
 

 
 
 
 

E n d End End

M o r e More More

你可能感兴趣的:(bugMaker,JavaWeb,Sharding-JDBC,mysql,maven,redis)