reformat codes

pull/1/head
Zhang Peng 2019-10-24 18:06:28 +08:00
parent 25d9f5cf13
commit aba34051fa
49 changed files with 5209 additions and 5267 deletions

View File

@ -1,32 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# http://editorconfig.org
# 所有文件换行使用 Unix like 风格LFbat 文件使用 win 风格CRLF
# 缩进 java 4 个空格,其他所有文件 2 个空格
# EditorConfig 用于在 IDE 中检查代码的基本 Code Style
# @see: https://editorconfig.org/
# 配置说明:
# 所有文件换行使用 Unix 风格LF*.bat 文件使用 Windows 风格CRLF
# java / sh 文件缩进 4 个空格,其他所有文件缩进 2 个空格
root = true
[*]
# Unix-style newlines with a newline ending every file
end_of_line = lf
# Change these settings to your own preference
indent_size = 2
indent_style = space
indent_style = tab
max_line_length = 120
# We recommend you to keep these unchanged
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.bat]
[*.{bat, cmd}]
end_of_line = crlf
[*.java]
indent_size = 4
[*.sql]
[*.{java, groovy, kt, sh}]
indent_size = 4
[*.md]

View File

@ -1,6 +1,7 @@
<?xml version="1.0"?>
<project 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" xmlns="http://maven.apache.org/POM/4.0.0">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.dunwu</groupId>
<artifactId>javadb-h2</artifactId>

View File

@ -43,8 +43,7 @@ public class H2JdbcTest01 {
CONNECTION = DriverManager.getConnection(JDBC_URL3, USER, PASSWORD);
// 创建sql声明
STATEMENT = CONNECTION.createStatement();
}
catch (ClassNotFoundException | SQLException e) {
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@ -56,8 +55,7 @@ public class H2JdbcTest01 {
STATEMENT.close();
// 关闭连接
CONNECTION.close();
}
catch (SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
@ -85,8 +83,7 @@ public class H2JdbcTest01 {
while (rs.next()) {
System.out.println(rs.getString("id") + "," + rs.getString("name") + "," + rs.getString("sex"));
}
}
catch (SQLException e) {
} catch (SQLException e) {
Assert.assertTrue(e.getMessage(), true);
}
}

View File

@ -1,6 +1,7 @@
<?xml version="1.0"?>
<project 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" xmlns="http://maven.apache.org/POM/4.0.0">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.dunwu</groupId>
<artifactId>javadb-hbase</artifactId>

View File

@ -21,5 +21,4 @@ public enum HBaseConstant {
public String key() {
return key;
}
}

View File

@ -4,7 +4,7 @@ package io.github.dunwu.javadb;
* HBase Cell
*
* @author Zhang Peng
* @date 2019-03-04
* @since 2019-03-04
*/
public class HbaseCellEntity {

View File

@ -16,13 +16,16 @@ import java.util.Properties;
* HBase
*
* @author Zhang Peng
* @date 2019-03-01
* @since 2019-03-01
*/
public class HbaseHelper {
private static final String FIRST_CONFIG = "classpath://config//hbase.properties";
private static final String SECOND_CONFIG = "classpath://application.properties";
private HbaseProperties hbaseProperties;
private Connection connection;
public HbaseHelper() throws Exception {
@ -52,25 +55,18 @@ public class HbaseHelper {
init(hbaseProperties);
}
public HbaseHelper(HbaseProperties hbaseProperties) throws Exception {
this.hbaseProperties = hbaseProperties;
init(hbaseProperties);
}
private Properties loadConfigFile() {
Properties properties = null;
try {
properties = PropertiesUtil.loadFromFile(FIRST_CONFIG);
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
if (properties == null) {
try {
properties = PropertiesUtil.loadFromFile(SECOND_CONFIG);
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
return null;
}
@ -95,18 +91,21 @@ public class HbaseHelper {
configuration.set(HBaseConstant.HBASE_IPC_POOL_SIZE.key(), hbaseProperties.getIpcPoolSize());
// @formatter:on
connection = ConnectionFactory.createConnection(configuration);
}
catch (Exception e) {
} catch (Exception e) {
throw new Exception("hbase链接未创建", e);
}
}
public HbaseHelper(HbaseProperties hbaseProperties) throws Exception {
this.hbaseProperties = hbaseProperties;
init(hbaseProperties);
}
public void destory() {
if (connection != null) {
try {
connection.close();
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
@ -125,12 +124,10 @@ public class HbaseHelper {
try {
if (StringUtils.isEmpty(tableName)) {
hTableDescriptors = connection.getAdmin().listTables();
}
else {
} else {
hTableDescriptors = connection.getAdmin().listTables(tableName);
}
}
catch (IOException e) {
} catch (IOException e) {
throw new Exception("执行失败", e);
}
return hTableDescriptors;
@ -145,7 +142,7 @@ public class HbaseHelper {
* </ul>
*/
public void createTable(String tableName) throws Exception {
createTable(tableName, new String[] { hbaseProperties.getColumnFamily() });
createTable(tableName, new String[] {hbaseProperties.getColumnFamily()});
}
/**
@ -173,8 +170,7 @@ public class HbaseHelper {
}
connection.getAdmin().createTable(tableDescriptor);
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
@ -187,6 +183,7 @@ public class HbaseHelper {
* <li>disable 'tablename'</li>
* <li>drop 't1'</li>
* </ul>
*
* @param name
*/
public void dropTable(String name) throws Exception {
@ -203,8 +200,7 @@ public class HbaseHelper {
admin.disableTable(tableName);
admin.deleteTable(tableName);
}
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
@ -230,8 +226,7 @@ public class HbaseHelper {
table = connection.getTable(TableName.valueOf(tableName));
Delete delete = new Delete(Bytes.toBytes(rowKey));
table.delete(delete);
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
throw new Exception("delete失败");
}
@ -279,14 +274,12 @@ public class HbaseHelper {
if (StringUtils.isNotEmpty(colFamily)) {
if (StringUtils.isNotEmpty(qualifier)) {
get.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(qualifier));
}
else {
} else {
get.addFamily(Bytes.toBytes(colFamily));
}
}
result = table.get(get);
}
catch (IOException e) {
} catch (IOException e) {
throw new Exception("查询时发生异常");
}
return result;
@ -333,11 +326,9 @@ public class HbaseHelper {
list.add(result);
result = resultScanner.next();
}
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
finally {
} finally {
if (resultScanner != null) {
resultScanner.close();
}
@ -366,8 +357,7 @@ public class HbaseHelper {
list.add(result);
result = resultScanner.next();
}
}
catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
return list;

View File

@ -8,7 +8,7 @@ import org.junit.Test;
/**
* @author Zhang Peng
* @date 2019-03-29
* @since 2019-03-29
*/
public class HbaseHelperTest {
@ -18,8 +18,7 @@ public class HbaseHelperTest {
public static void BeforeClass() {
try {
hbaseHelper = new HbaseHelper();
}
catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
@ -39,13 +38,13 @@ public class HbaseHelperTest {
@Test
public void createTable() throws Exception {
hbaseHelper.createTable("table1", new String[] { "columnFamliy1", "columnFamliy2" });
hbaseHelper.createTable("table1", new String[] {"columnFamliy1", "columnFamliy2"});
HTableDescriptor[] table1s = hbaseHelper.listTables("table1");
if (table1s == null || table1s.length <= 0) {
Assert.fail();
}
hbaseHelper.createTable("table2", new String[] { "columnFamliy1", "columnFamliy2" });
hbaseHelper.createTable("table2", new String[] {"columnFamliy1", "columnFamliy2"});
table1s = hbaseHelper.listTables("table2");
if (table1s == null || table1s.length <= 0) {
Assert.fail();

View File

@ -1,6 +1,7 @@
<?xml version="1.0"?>
<project 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" xmlns="http://maven.apache.org/POM/4.0.0">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.dunwu</groupId>
<artifactId>javadb-mysql</artifactId>

View File

@ -6,8 +6,6 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
/**
* Mysql
*
@ -17,11 +15,17 @@ import java.sql.*;
public class MysqlDemoTest {
private static final String DB_HOST = "localhost";
private static final String DB_PORT = "3306";
private static final String DB_SCHEMA = "sakila";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
private static Logger logger = LoggerFactory.getLogger(MysqlDemoTest.class);
private static Statement statement;
private static Connection connection;
@ -35,8 +39,7 @@ public class MysqlDemoTest {
// DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila?" +
// "user=root&password=root");
statement = connection.createStatement();
}
catch (SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
@ -47,8 +50,7 @@ public class MysqlDemoTest {
if (connection != null) {
connection.close();
}
}
catch (SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
@ -69,8 +71,7 @@ public class MysqlDemoTest {
logger.debug("actor_id: {}, first_name: {}, last_name: {}, last_update: {}", id, firstName, lastName,
lastUpdate.toLocalDate());
}
}
catch (SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}

View File

@ -3,7 +3,7 @@
<!-- logback中一共有5种有效级别分别是TRACE、DEBUG、INFO、WARN、ERROR优先级依次从低到高 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="FILE_NAME" value="javadb"/>
<property name="FILE_NAME" value="javadb" />
<!-- 将记录日志打印到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
@ -34,11 +34,11 @@
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="TRACE">
<appender-ref ref="ALL"/>
<appender-ref ref="ALL" />
</logger>
<root level="TRACE">
<appender-ref ref="STDOUT"/>
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->

View File

@ -1,6 +1,7 @@
<?xml version="1.0"?>
<project 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" xmlns="http://maven.apache.org/POM/4.0.0">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.dunwu</groupId>
<artifactId>javadb-redis</artifactId>

View File

@ -38,8 +38,7 @@ public class JedisDemoTest {
try {
jedis.ping();
logger.debug("jedis 连接成功。");
}
catch (JedisConnectionException e) {
} catch (JedisConnectionException e) {
e.printStackTrace();
}
}

View File

@ -20,7 +20,7 @@ import java.util.Set;
*/
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
public class JedisPoolDemoTest {
private static Logger logger = LoggerFactory.getLogger(JedisPoolDemoTest.class);

View File

@ -7,7 +7,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Zhang Peng
* @date 2018/6/19
* @since 2018/6/19
*/
public class RedissonStandaloneTest {

View File

@ -6,7 +6,7 @@
<description>Spring基础配置</description>
<import resource="classpath:/config.xml"/>
<import resource="classpath:/redis.xml"/>
<import resource="classpath:/config.xml" />
<import resource="classpath:/redis.xml" />
</beans>

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
@ -7,13 +8,13 @@
<!-- 开发环境配置文件 -->
<beans profile="dev">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/properties/application.properties,
classpath*:/properties/application-dev.properties"/>
classpath*:/properties/application-dev.properties" />
</beans>
<!-- 测试环境配置文件 -->
<beans profile="test">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/properties/application.properties,
classpath*:/properties/application-test.properties"/>
classpath*:/properties/application-test.properties" />
</beans>
</beans>

View File

@ -3,7 +3,7 @@
<!-- logback中一共有5种有效级别分别是TRACE、DEBUG、INFO、WARN、ERROR优先级依次从低到高 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="FILE_NAME" value="javadb"/>
<property name="FILE_NAME" value="javadb" />
<!-- 将记录日志打印到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
@ -34,11 +34,11 @@
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="TRACE">
<appender-ref ref="ALL"/>
<appender-ref ref="ALL" />
</logger>
<root level="TRACE">
<appender-ref ref="STDOUT"/>
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->

View File

@ -4,5 +4,4 @@ redis.port = 6379
redis.timeout = 3000
redis.password = zp
redis.database = 0
log.path = ./

View File

@ -4,5 +4,4 @@ redis.port = 6379
redis.timeout = 3000
redis.password = zp
redis.database = 0
log.path = /home/zp/log

View File

@ -6,16 +6,16 @@
<!-- redis配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${jedis.pool.maxTotal}"/>
<property name="maxIdle" value="${jedis.pool.maxIdle}"/>
<property name="maxWaitMillis" value="${jedis.pool.maxWaitMillis}"/>
<property name="testOnBorrow" value="${jedis.pool.testOnBorrow}"/>
<property name="maxTotal" value="${jedis.pool.maxTotal}" />
<property name="maxIdle" value="${jedis.pool.maxIdle}" />
<property name="maxWaitMillis" value="${jedis.pool.maxWaitMillis}" />
<property name="testOnBorrow" value="${jedis.pool.testOnBorrow}" />
</bean>
<!-- jedis pool配置 -->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy" depends-on="jedisPoolConfig">
<constructor-arg ref="jedisPoolConfig"/>
<constructor-arg type="java.lang.String" value="${redis.host}"/>
<constructor-arg type="int" value="${redis.port}"/>
<constructor-arg ref="jedisPoolConfig" />
<constructor-arg type="java.lang.String" value="${redis.host}" />
<constructor-arg type="int" value="${redis.port}" />
</bean>
</beans>

View File

@ -5,7 +5,7 @@
http://www.springframework.org/schema/beans/spring-beans.xsd
http://redisson.org/schema/redisson
http://redisson.org/schema/redisson/redisson.xsd">
<bean id="stringCodec" class="org.redisson.client.codec.StringCodec"/>
<bean id="stringCodec" class="org.redisson.client.codec.StringCodec" />
<redisson:client id="standalone"
name="aliasName1,aliasName2"
codec-ref="stringCodec">
@ -16,6 +16,6 @@
timeout="3000"
ping-timeout="30000"
reconnection-timeout="30000"
database="0"/>
database="0" />
</redisson:client>
</beans>

View File

@ -5,7 +5,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
/**
* @author Zhang Peng
* @date 2019-03-05
* @since 2019-03-05
*/
public class SqliteApplication implements CommandLineRunner {

View File

@ -7,10 +7,38 @@ import java.sql.Statement;
/**
* @author Zhang Peng
* @date 2019-03-05
* @since 2019-03-05
*/
public class SqliteDemo {
public static void main(String[] args) {
SqliteDemo.dropTable();
SqliteDemo.createTable();
SqliteDemo.insert();
SqliteDemo.select();
SqliteDemo.delete();
SqliteDemo.select();
SqliteDemo.update();
SqliteDemo.select();
}
public static void dropTable() {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement statement = connection.createStatement();
String sql = new StringBuilder().append("DROP TABLE IF EXISTS COMPANY;").toString();
statement.executeUpdate(sql);
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Drop table successfully.");
}
public static void createTable() {
try {
Class.forName("org.sqlite.JDBC");
@ -23,32 +51,13 @@ public class SqliteDemo {
statement.executeUpdate(sql);
statement.close();
connection.close();
}
catch (Exception e) {
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Create table successfully.");
}
public static void dropTable() {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement statement = connection.createStatement();
String sql = new StringBuilder().append("DROP TABLE IF EXISTS COMPANY;").toString();
statement.executeUpdate(sql);
statement.close();
connection.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Drop table successfully.");
}
public static void insert() {
try {
Class.forName("org.sqlite.JDBC");
@ -73,62 +82,13 @@ public class SqliteDemo {
statement.close();
connection.commit();
connection.close();
}
catch (Exception e) {
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Insert table successfully.");
}
public static void delete() {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
statement.executeUpdate(sql);
String sql2 = "DELETE from COMPANY where ID=3;";
statement.executeUpdate(sql2);
String sql3 = "DELETE from COMPANY where ID=4;";
statement.executeUpdate(sql3);
connection.commit();
statement.close();
connection.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Delete table successfully.");
}
public static void update() {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
statement.executeUpdate(sql);
connection.commit();
statement.close();
connection.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Update table successfully.");
}
public static void select() {
try {
Class.forName("org.sqlite.JDBC");
@ -150,22 +110,56 @@ public class SqliteDemo {
resultSet.close();
statement.close();
connection.close();
}
catch (Exception e) {
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
public static void main(String[] args) {
SqliteDemo.dropTable();
SqliteDemo.createTable();
SqliteDemo.insert();
SqliteDemo.select();
SqliteDemo.delete();
SqliteDemo.select();
SqliteDemo.update();
SqliteDemo.select();
public static void delete() {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
statement.executeUpdate(sql);
String sql2 = "DELETE from COMPANY where ID=3;";
statement.executeUpdate(sql2);
String sql3 = "DELETE from COMPANY where ID=4;";
statement.executeUpdate(sql3);
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Delete table successfully.");
}
public static void update() {
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
statement.executeUpdate(sql);
connection.commit();
statement.close();
connection.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Update table successfully.");
}
}

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="io.github.dunwu" level="DEBUG"/>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="io.github.dunwu" level="DEBUG" />
</configuration>

View File

@ -1,6 +1,7 @@
<?xml version="1.0"?>
<project 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" xmlns="http://maven.apache.org/POM/4.0.0">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.dunwu</groupId>
<artifactId>db-middleware-flyway</artifactId>

View File

@ -567,6 +567,7 @@ class StreamingAPIServer(
# 关闭所有客户端请求线程。
daemon_threads = True
# 创建一个名为 StreamingAPIRequestHandler 的类。

View File

@ -1,6 +1,7 @@
<?xml version="1.0"?>
<project 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" xmlns="http://maven.apache.org/POM/4.0.0">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.dunwu</groupId>
<artifactId>redis-in-action</artifactId>

View File

@ -40,38 +40,13 @@ public class Chapter01 {
printArticles(articles);
assert articles.size() >= 1;
addRemoveGroups(conn, articleId, new String[] { "new-group" }, new String[] {});
addRemoveGroups(conn, articleId, new String[] {"new-group"}, new String[] {});
System.out.println("We added the article to a new group, other articles include:");
articles = getGroupArticles(conn, "new-group", 1);
printArticles(articles);
assert articles.size() >= 1;
}
/**
* 1-6
*/
public void articleVote(Jedis conn, String user, String article) {
// 计算文章的投票截止时间。
long cutoff = (System.currentTimeMillis() / 1000) - ONE_WEEK_IN_SECONDS;
// 检查是否还可以对文章进行投票
// (虽然使用散列也可以获取文章的发布时间,
// 但有序集合返回的文章发布时间为浮点数,
// 可以不进行转换直接使用)。
if (conn.zscore("time:", article) < cutoff) {
return;
}
// 从article:id标识符identifier里面取出文章的ID。
String articleId = article.substring(article.indexOf(':') + 1);
// 如果用户是第一次为这篇文章投票,那么增加这篇文章的投票数量和评分。
if (conn.sadd("voted:" + articleId, user) == 1) {
conn.zincrby("score:", VOTE_SCORE, article);
conn.hincrBy(article, "votes", 1);
}
}
/**
* 1-7
*/
@ -103,10 +78,67 @@ public class Chapter01 {
return articleId;
}
/**
* 1-6
*/
public void articleVote(Jedis conn, String user, String article) {
// 计算文章的投票截止时间。
long cutoff = (System.currentTimeMillis() / 1000) - ONE_WEEK_IN_SECONDS;
// 检查是否还可以对文章进行投票
// (虽然使用散列也可以获取文章的发布时间,
// 但有序集合返回的文章发布时间为浮点数,
// 可以不进行转换直接使用)。
if (conn.zscore("time:", article) < cutoff) {
return;
}
// 从article:id标识符identifier里面取出文章的ID。
String articleId = article.substring(article.indexOf(':') + 1);
// 如果用户是第一次为这篇文章投票,那么增加这篇文章的投票数量和评分。
if (conn.sadd("voted:" + articleId, user) == 1) {
conn.zincrby("score:", VOTE_SCORE, article);
conn.hincrBy(article, "votes", 1);
}
}
public List<Map<String, String>> getArticles(Jedis conn, int page) {
return getArticles(conn, page, "score:");
}
private void printArticles(List<Map<String, String>> articles) {
for (Map<String, String> article : articles) {
System.out.println(" id: " + article.get("id"));
for (Map.Entry<String, String> entry : article.entrySet()) {
if (entry.getKey().equals("id")) {
continue;
}
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
}
}
/**
* 1-9
*/
public void addRemoveGroups(Jedis conn, String articleId, String[] toAdd, String[] toRemove) {
// 构建存储文章信息的键名。
String article = "article:" + articleId;
// 将文章添加到它所属的群组里面。
for (String group : toAdd) {
conn.sadd("group:" + group, article);
}
// 从群组里面移除文章。
for (String group : toRemove) {
conn.srem("group:" + group, article);
}
}
public List<Map<String, String>> getGroupArticles(Jedis conn, String group, int page) {
return getGroupArticles(conn, group, page, "score:");
}
/**
* 1-8
*/
@ -128,26 +160,6 @@ public class Chapter01 {
return articles;
}
/**
* 1-9
*/
public void addRemoveGroups(Jedis conn, String articleId, String[] toAdd, String[] toRemove) {
// 构建存储文章信息的键名。
String article = "article:" + articleId;
// 将文章添加到它所属的群组里面。
for (String group : toAdd) {
conn.sadd("group:" + group, article);
}
// 从群组里面移除文章。
for (String group : toRemove) {
conn.srem("group:" + group, article);
}
}
public List<Map<String, String>> getGroupArticles(Jedis conn, String group, int page) {
return getGroupArticles(conn, group, page, "score:");
}
/**
* 1-10
*/
@ -166,16 +178,4 @@ public class Chapter01 {
return getArticles(conn, page, key);
}
private void printArticles(List<Map<String, String>> articles) {
for (Map<String, String> article : articles) {
System.out.println(" id: " + article.get("id"));
for (Map.Entry<String, String> entry : article.entrySet()) {
if (entry.getKey().equals("id")) {
continue;
}
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
}
}
}

View File

@ -193,8 +193,7 @@ public class Chapter02 {
if (count <= 0) {
// 从购物车里面移除指定的商品。
conn.hdel("cart:" + session, item);
}
else {
} else {
// 将指定的商品添加到购物车。
conn.hset("cart:" + session, item, String.valueOf(count));
}
@ -259,8 +258,7 @@ public class Chapter02 {
Long rank = conn.zrank("viewed:", itemId);
// 根据商品的浏览次数排名来判断是否需要缓存这个页面。
return rank != null && rank < 10000;
}
catch (MalformedURLException mue) {
} catch (MalformedURLException mue) {
return false;
}
}
@ -283,7 +281,6 @@ public class Chapter02 {
}
public static class Inventory {
private String id;
@ -304,7 +301,6 @@ public class Chapter02 {
}
/**
* 2-3
*/
@ -335,8 +331,7 @@ public class Chapter02 {
if (size <= limit) {
try {
sleep(1000);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
continue;
@ -362,7 +357,6 @@ public class Chapter02 {
}
/**
* 2-5
*/
@ -391,8 +385,7 @@ public class Chapter02 {
if (size <= limit) {
try {
sleep(1000);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
continue;
@ -417,7 +410,6 @@ public class Chapter02 {
}
/**
* 2-8
*/
@ -449,8 +441,7 @@ public class Chapter02 {
try {
// 暂时没有行需要被缓存休眠50毫秒后重试。
sleep(50);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
continue;

View File

@ -160,9 +160,9 @@ public class Chapter04 {
public void benchmarkUpdateToken(Jedis conn, int duration) {
try {
@SuppressWarnings("rawtypes")
Class[] args = new Class[] { Jedis.class, String.class, String.class, String.class };
Method[] methods = new Method[] { this.getClass().getDeclaredMethod("updateToken", args),
this.getClass().getDeclaredMethod("updateTokenPipeline", args), };
Class[] args = new Class[] {Jedis.class, String.class, String.class, String.class}
Method[] methods = new Method[] {this.getClass().getDeclaredMethod("updateToken", args),
this.getClass().getDeclaredMethod("updateTokenPipeline", args),}
for (Method method : methods) {
int count = 0;
long start = System.currentTimeMillis();
@ -175,8 +175,7 @@ public class Chapter04 {
System.out.println(
method.getName() + ' ' + count + ' ' + (delta / 1000) + ' ' + (count / (delta / 1000)));
}
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}

View File

@ -281,7 +281,7 @@
// updateCounter(conn, name, count, System.currentTimeMillis() / 1000);
// }
//
// public static final int[] PRECISION = new int[]{1, 5, 60, 300, 3600, 18000, 86400};
// public static final int[] PRECISION = new int[]{1, 5, 60, 300, 3600, 18000, 86400}
// public void updateCounter(Jedis conn, String name, int count, long now){
// Transaction trans = conn.multi();
// for (int prec : PRECISION) {

View File

@ -5,8 +5,6 @@ import redis.clients.jedis.Transaction;
import redis.clients.jedis.Tuple;
import redis.clients.jedis.ZParams;
import java.io.*;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
@ -92,7 +90,7 @@ public class Chapter06 {
System.out.println();
System.out.println("Let's add a few people to the guild");
for (String name : new String[] { "jeff", "jenny", "jack", "jennifer" }) {
for (String name : new String[] {"jeff", "jenny", "jack", "jennifer"}) {
joinGuild(conn, "test", name);
}
System.out.println();
@ -172,7 +170,7 @@ public class Chapter06 {
System.out.println("\n----- testDelayedTasks -----");
conn.del("queue:tqueue", "delayed:");
System.out.println("Let's start some regular and delayed tasks...");
for (long delay : new long[] { 0, 500, 0, 1500 }) {
for (long delay : new long[] {0, 500, 0, 1500}) {
assert executeLater(conn, "tqueue", "testfn", new ArrayList<String>(), delay) != null;
}
long r = conn.llen("queue:tqueue");
@ -341,7 +339,7 @@ public class Chapter06 {
String start = prefix.substring(0, prefix.length() - 1) + suffix + '{';
String end = prefix + '{';
// 返回范围。
return new String[] { start, end };
return new String[] {start, end}
}
public void joinGuild(Jedis conn, String guild, String user) {
@ -394,7 +392,7 @@ public class Chapter06 {
// 如果有其他自动补完操作正在执行,
// 那么从获取到的元素里面移除起始元素和终结元素。
for (Iterator<String> iterator = items.iterator(); iterator.hasNext();) {
for (Iterator<String> iterator = items.iterator(); iterator.hasNext(); ) {
if (iterator.next().indexOf('{') != -1) {
iterator.remove();
}
@ -422,8 +420,7 @@ public class Chapter06 {
try {
Thread.sleep(1);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
@ -452,8 +449,7 @@ public class Chapter06 {
try {
Thread.sleep(1);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
@ -540,11 +536,10 @@ public class Chapter06 {
Gson gson = new Gson();
String identifier = UUID.randomUUID().toString();
String itemArgs = gson.toJson(args);
String item = gson.toJson(new String[] { identifier, queue, name, itemArgs });
String item = gson.toJson(new String[] {identifier, queue, name, itemArgs});
if (delay > 0) {
conn.zadd("delayed:", System.currentTimeMillis() + delay, item);
}
else {
} else {
conn.rpush("queue:" + queue, item);
}
return identifier;
@ -582,8 +577,7 @@ public class Chapter06 {
values.put("message", message);
String packed = new Gson().toJson(values);
conn.zadd("msgs:" + chatId, messageId, packed);
}
finally {
} finally {
releaseLock(conn, "chat:" + chatId, identifier);
}
return chatId;
@ -632,11 +626,11 @@ public class Chapter06 {
}
conn.zadd("chat:" + chatId, seenId, recipient);
seenUpdates.add(new Object[] { "seen:" + recipient, seenId, chatId });
seenUpdates.add(new Object[] {"seen:" + recipient, seenId, chatId});
Set<Tuple> minIdSet = conn.zrangeWithScores("chat:" + chatId, 0, 0);
if (minIdSet.size() > 0) {
msgRemoves.add(new Object[] { "msgs:" + chatId, minIdSet.iterator().next().getScore() });
msgRemoves.add(new Object[] {"msgs:" + chatId, minIdSet.iterator().next().getScore()});
}
chatMessages.add(new ChatMessages(chatId, messages));
}
@ -681,8 +675,7 @@ public class Chapter06 {
callback.callback(line);
}
callback.callback(null);
}
finally {
} finally {
reader.close();
}
@ -702,10 +695,10 @@ public class Chapter06 {
}
public class TestCallback implements Callback {
public List<Integer> counts = new ArrayList<Integer>();
private int index;
public void callback(String line) {
@ -721,7 +714,6 @@ public class Chapter06 {
}
public class RedisInputStream extends InputStream {
private Jedis conn;
@ -769,7 +761,6 @@ public class Chapter06 {
}
public class ChatMessages {
public String chatId;
@ -815,8 +806,7 @@ public class Chapter06 {
if (item == null || item.getScore() > System.currentTimeMillis()) {
try {
sleep(10);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.interrupted();
}
continue;
@ -884,12 +874,10 @@ public class Chapter06 {
long cleaned = clean(waiting, count);
if (cleaned != 0) {
bytesInRedis -= cleaned;
}
else {
} else {
try {
sleep(250);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.interrupted();
}
}
@ -905,21 +893,17 @@ public class Chapter06 {
byte[] bytes = new byte[read];
System.arraycopy(buffer, 0, bytes, 0, read);
conn.append((channel + logFile).getBytes(), bytes);
}
else {
} else {
conn.append((channel + logFile).getBytes(), buffer);
}
}
}
catch (IOException ioe) {
} catch (IOException ioe) {
ioe.printStackTrace();
throw new RuntimeException(ioe);
}
finally {
} finally {
try {
in.close();
}
catch (Exception ignore) {
} catch (Exception ignore) {
}
}
@ -935,12 +919,10 @@ public class Chapter06 {
long cleaned = clean(waiting, count);
if (cleaned != 0) {
bytesInRedis -= cleaned;
}
else {
} else {
try {
sleep(250);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.interrupted();
}
}

View File

@ -267,7 +267,7 @@
// indexAd(conn, "1", new String[]{"USA", "CA"}, CONTENT, Ecpm.CPC, .25);
// indexAd(conn, "2", new String[]{"USA", "VA"}, CONTENT + " wooooo", Ecpm.CPC, .125);
//
// String[] usa = new String[]{"USA"};
// String[] usa = new String[]{"USA"}
// for (int i = 0; i < 100; i++) {
// targetAds(conn, usa, CONTENT);
// }
@ -526,7 +526,7 @@
// int updateWeight = weights.containsKey("update") ? weights.get("update") : 1;
// int voteWeight = weights.containsKey("vote") ? weights.get("vote") : 0;
//
// String[] keys = new String[]{id, "sort:update", "sort:votes"};
// String[] keys = new String[]{id, "sort:update", "sort:votes"}
// Transaction trans = conn.multi();
// id = zintersect(
// trans, ttl, new ZParams().weights(0, updateWeight, voteWeight), keys);

View File

@ -145,15 +145,13 @@ public class Chapter08 {
if (conn.setnx(lockName, id) >= 1) {
conn.expire(lockName, lockTimeout);
return id;
}
else if (conn.ttl(lockName) <= 0) {
} else if (conn.ttl(lockName) <= 0) {
conn.expire(lockName, lockTimeout);
}
try {
Thread.sleep(1);
}
catch (InterruptedException ie) {
} catch (InterruptedException ie) {
Thread.interrupted();
}
}
@ -357,8 +355,7 @@ public class Chapter08 {
Method method = getClass().getDeclaredMethod("syndicateStatus", Jedis.class, Long.TYPE, Long.TYPE,
Long.TYPE, Double.TYPE);
executeLater("default", method, uid, postId, postTime, start);
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@ -384,8 +381,7 @@ public class Chapter08 {
trans.exec();
return true;
}
finally {
} finally {
releaseLock(conn, key, lock);
}
}
@ -455,8 +451,7 @@ public class Chapter08 {
Method method = getClass().getDeclaredMethod("refillTimeline", Jedis.class, String.class, String.class,
Double.TYPE);
executeLater("default", method, incoming, timeline, start);
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@ -487,16 +482,13 @@ public class Chapter08 {
try {
method = getClass().getDeclaredMethod("cleanTimelines", Jedis.class, Long.TYPE, Long.TYPE, Double.TYPE,
Boolean.TYPE);
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
if (followers.size() >= POSTS_PER_PASS) {
executeLater("default", method, uid, statusId, start, onLists);
}
else if (!onLists) {
} else if (!onLists) {
executeLater("default", method, uid, statusId, 0, true);
}
}
@ -530,8 +522,7 @@ public class Chapter08 {
try {
method.invoke(instance, args);
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}

View File

@ -10,7 +10,8 @@ import java.util.zip.CRC32;
public class Chapter09 {
private static final String[] COUNTRIES = ("ABW AFG AGO AIA ALA ALB AND ARE ARG ARM ASM ATA ATF ATG AUS AUT AZE BDI "
private static final String[] COUNTRIES =
("ABW AFG AGO AIA ALA ALB AND ARE ARG ARM ASM ATA ATF ATG AUS AUT AZE BDI "
+ "BEL BEN BES BFA BGD BGR BHR BHS BIH BLM BLR BLZ BMU BOL BRA BRB BRN BTN "
+ "BVT BWA CAF CAN CCK CHE CHL CHN CIV CMR COD COG COK COL COM CPV CRI CUB "
+ "CUW CXR CYM CYP CZE DEU DJI DMA DNK DOM DZA ECU EGY ERI ESH ESP EST ETH "
@ -26,7 +27,9 @@ public class Chapter09 {
+ "USA UZB VAT VCT VEN VGB VIR VNM VUT WLF WSM YEM ZAF ZMB ZWE").split(" ");
private static final Map<String, String[]> STATES = new HashMap<String, String[]>();
private static final SimpleDateFormat ISO_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:00:00");
static {
STATES.put("CAN", "AB BC MB NB NL NS NT NU ON PE QC SK YT".split(" "));
STATES.put("USA",
@ -34,12 +37,17 @@ public class Chapter09 {
+ "KS KY LA MA MD ME MH MI MN MO MP MS MT NC ND NE NH NJ NM NV NY OH "
+ "OK OR PA PR PW RI SC SD TN TX UT VA VI VT WA WI WV WY").split(" "));
}
static {
ISO_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private int SHARD_SIZE = 512;
private long DAILY_EXPECTED = 1000000;
private Map<String, Long> EXPECTED = new HashMap<String, Long>();
private long USERS_PER_SHARD = (long) Math.pow(2, 20);
public static final void main(String[] args) {
@ -135,8 +143,7 @@ public class Chapter09 {
setLocation(conn, i, country, state);
i++;
}
}
else {
} else {
setLocation(conn, i, country, "");
i++;
}
@ -160,8 +167,7 @@ public class Chapter09 {
for (String state : STATES.get(country)) {
assert states.get(country).get(state) == 1;
}
}
else {
} else {
assert countries.get(country) == 1;
}
}
@ -189,8 +195,7 @@ public class Chapter09 {
long shardId = 0;
if (isDigit(key)) {
shardId = Integer.parseInt(key, 10) / shardSize;
}
else {
} else {
CRC32 crc = new CRC32();
crc.update(key.getBytes());
long shards = 2 * totalElements / shardSize;
@ -241,8 +246,7 @@ public class Chapter09 {
expectedStr = conn.get(exkey);
expected = Integer.parseInt(expectedStr);
}
}
else {
} else {
expected = Long.parseLong(expectedStr);
}
@ -287,15 +291,12 @@ public class Chapter09 {
updateAggregates(countries, states, code);
}
}
}
catch (IOException ioe) {
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
finally {
} finally {
try {
in.close();
}
catch (Exception e) {
} catch (Exception e) {
// ignore
}
}
@ -390,7 +391,7 @@ public class Chapter09 {
}
sindex++;
return new String(new char[] { (char) cindex, (char) sindex });
return new String(new char[] {(char) cindex, (char) sindex});
}
private int bisectLeft(String[] values, String key) {