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;
@ -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();
}
}

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

@ -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

@ -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

@ -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">

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

@ -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,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

@ -47,31 +47,6 @@ public class Chapter01 {
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 };
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), };
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;
@ -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) {
@ -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();
}
}
@ -543,8 +539,7 @@ public class Chapter06 {
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;
@ -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
}
}