feat: 更新示例代码

pull/13/head
dunwu 2022-01-10 10:15:31 +08:00
parent 0b97adce78
commit 16a41f1520
27 changed files with 761 additions and 439 deletions

View File

@ -14,7 +14,7 @@
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>
@ -39,7 +39,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>2.0.206</version>
<scope>test</scope>
</dependency>
<!-- database end -->

View File

@ -15,7 +15,7 @@
<maven.compiler.target>${java.version}</maven.compiler.target>
<hbase.version>1.3.1</hbase.version>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
<dunwu.version>0.5.7</dunwu.version>
</properties>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">
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>
<parent>
@ -15,111 +15,32 @@
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring.version>4.3.13.RELEASE</spring.version>
<logback.version>1.2.3</logback.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- db begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- db end -->
<!-- log start -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!-- log end -->
<!-- spring begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring end -->
<!-- test begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!-- test end -->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- database begin -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!-- database end -->
<!-- log begin -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-parent</artifactId>
<version>${logback.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- log end -->
<!-- test begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- test end -->
</dependencies>
</dependencyManagement>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>logback.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,45 @@
package io.github.dunwu.javadb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Connection;
import javax.sql.DataSource;
@Slf4j
@SpringBootApplication
public class SpringBootDataJdbcApplication implements CommandLineRunner {
private final JdbcTemplate jdbcTemplate;
public SpringBootDataJdbcApplication(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootDataJdbcApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
DataSource dataSource = jdbcTemplate.getDataSource();
Connection connection;
if (dataSource != null) {
connection = dataSource.getConnection();
} else {
log.error("连接数据源失败!");
return;
}
if (connection != null) {
log.info("数据源 Url: {}", connection.getMetaData().getURL());
} else {
log.error("连接数据源失败!");
}
}
}

View File

@ -0,0 +1,63 @@
package io.github.dunwu.javadb;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Objects;
/**
* user
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2019-11-18
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String address;
private String email;
public User(String name, Integer age, String address, String email) {
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
User user = (User) o;
if (id != null && id.equals(user.id)) {
return true;
}
return name.equals(user.name);
}
}

View File

@ -0,0 +1,41 @@
package io.github.dunwu.javadb;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* user Dao
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2019-11-18
*/
public interface UserDao {
// DML
// -------------------------------------------------------------------
void insert(User user);
void batchInsert(List<User> users);
void deleteByName(String name);
void deleteAll();
void update(User user);
Integer count();
List<User> list();
User queryByName(String name);
JdbcTemplate getJdbcTemplate();
// DDL
// -------------------------------------------------------------------
void truncate();
void recreateTable();
}

View File

@ -0,0 +1,36 @@
package io.github.dunwu.javadb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import javax.annotation.PostConstruct;
/**
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2020-10-11
*/
@Slf4j
@Component
public class UserDaoExecutor {
private final UserDao userDao;
public UserDaoExecutor(UserDao userDao) {
this.userDao = userDao;
}
@PostConstruct
public void method() {
if (userDao != null) {
log.info("Connect to datasource success.");
} else {
log.error("Connect to datasource failed!");
return;
}
List<User> list = userDao.list();
list.forEach(item -> log.info(item.toString()));
}
}

View File

@ -0,0 +1,114 @@
package io.github.dunwu.javadb;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* user Dao
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2019-11-18
*/
@Repository
public class UserDaoImpl implements UserDao {
private final JdbcTemplate jdbcTemplate;
public UserDaoImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void insert(User user) {
jdbcTemplate.update("INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)",
user.getName(), user.getAge(), user.getAddress(), user.getEmail());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void batchInsert(List<User> users) {
String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)";
List<Object[]> params = new ArrayList<>();
users.forEach(user -> {
params.add(new Object[] { user.getName(), user.getAge(), user.getAddress(), user.getEmail() });
});
jdbcTemplate.batchUpdate(sql, params);
}
@Override
public void deleteByName(String name) {
jdbcTemplate.update("DELETE FROM user WHERE name = ?", name);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAll() {
jdbcTemplate.execute("DELETE FROM user");
}
@Override
public void update(User user) {
jdbcTemplate.update("UPDATE user SET name=?, age=?, address=?, email=? WHERE id=?",
user.getName(), user.getAge(), user.getAddress(), user.getEmail(), user.getId());
}
@Override
public Integer count() {
try {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM user", Integer.class);
} catch (EmptyResultDataAccessException e) {
return null;
}
}
@Override
public List<User> list() {
return jdbcTemplate.query("SELECT * FROM user", new BeanPropertyRowMapper<>(User.class));
}
@Override
public User queryByName(String name) {
try {
return jdbcTemplate.queryForObject("SELECT * FROM user WHERE name = ?",
new BeanPropertyRowMapper<>(User.class), name);
} catch (EmptyResultDataAccessException e) {
return null;
}
}
@Override
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Override
public void truncate() {
jdbcTemplate.execute("TRUNCATE TABLE user");
}
@Override
public void recreateTable() {
jdbcTemplate.execute("DROP TABLE IF EXISTS user");
String sqlStatement =
"CREATE TABLE user (\n"
+ " id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',\n"
+ " name VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',\n"
+ " age INT(3) NOT NULL DEFAULT 0 COMMENT '年龄',\n"
+ " address VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',\n"
+ " email VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',\n"
+ " PRIMARY KEY (id),\n"
+ " UNIQUE (name)\n"
+ ");";
jdbcTemplate.execute(sqlStatement);
}
}

View File

@ -0,0 +1,8 @@
spring.datasource.url = jdbc:mysql://localhost:3306/db_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = root
# 强制每次启动使用 sql 初始化数据,本项目仅为了演示方便,真实环境应避免这种模式
spring.datasource.initialization-mode = ALWAYS
spring.datasource.schema = classpath:sql/schema.sql
spring.datasource.data = classpath:sql/data.sql

View File

@ -0,0 +1,12 @@
${AnsiColor.BRIGHT_YELLOW}${AnsiStyle.BOLD}
________ ___ ___ ________ ___ __ ___ ___
|\ ___ \|\ \|\ \|\ ___ \|\ \ |\ \|\ \|\ \
\ \ \_|\ \ \ \\\ \ \ \\ \ \ \ \ \ \ \ \ \\\ \
\ \ \ \\ \ \ \\\ \ \ \\ \ \ \ \ __\ \ \ \ \\\ \
\ \ \_\\ \ \ \\\ \ \ \\ \ \ \ \|\__\_\ \ \ \\\ \
\ \_______\ \_______\ \__\\ \__\ \____________\ \_______\
\|_______|\|_______|\|__| \|__|\|____________|\|_______|
${AnsiColor.CYAN}${AnsiStyle.BOLD}
:: Java :: (v${java.version})
:: Spring Boot :: (v${spring-boot.version})
${AnsiStyle.NORMAL}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%boldYellow(%thread)] [%highlight(%-5level)] %boldGreen(%c{36}.%M) - %boldBlue(%m%n)
</pattern>
</encoder>
</appender>
<logger name="io.github.dunwu.javadb" level="INFO" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@ -0,0 +1,10 @@
-- -------------------------------------------------------------------
-- 运行本项目的初始化 DML 脚本
-- Mysql 知识点可以参考:
-- https://dunwu.github.io/db-tutorial/#/sql/mysql/README
-- -------------------------------------------------------------------
INSERT INTO `user` (`name`, `age`, `address`, `email`)
VALUES ('张三', 18, '北京', 'xxx@163.com');
INSERT INTO `user` (`name`, `age`, `address`, `email`)
VALUES ('李四', 19, '上海', 'xxx@163.com');

View File

@ -0,0 +1,18 @@
-- -------------------------------------------------------------------
-- 运行本项目的初始化 DDL 脚本
-- Mysql 知识点可以参考:
-- https://dunwu.github.io/db-tutorial/#/sql/mysql/README
-- -------------------------------------------------------------------
-- 创建用户表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',
`age` INT(3) NOT NULL DEFAULT 0 COMMENT '年龄',
`address` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',
`email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',
PRIMARY KEY (`id`),
UNIQUE (`name`)
);

View File

@ -16,66 +16,63 @@ import java.sql.*;
*/
public class MysqlDemoTest {
private static final String DB_HOST = "localhost";
private static final String DB_HOST = "localhost";
private static final String DB_PORT = "3306";
private static final String DB_PORT = "3306";
private static final String DB_SCHEMA = "sakila";
private static final String DB_SCHEMA = "db_tutorial";
private static final String DB_USER = "root";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
private static final String DB_PASSWORD = "root";
private static Logger logger = LoggerFactory.getLogger(MysqlDemoTest.class);
private static Logger logger = LoggerFactory.getLogger(MysqlDemoTest.class);
private static Statement statement;
private static Statement statement;
private static Connection connection;
private static Connection connection;
@BeforeClass
public static void beforeClass() {
try {
final String DB_URL = String.format("jdbc:mysql://%s:%s/%s", DB_HOST, DB_PORT, DB_SCHEMA);
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
// connection =
// DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila?" +
// "user=root&password=root");
statement = connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
@BeforeClass
public static void beforeClass() {
try {
final String DB_URL = String.format("jdbc:mysql://%s:%s/%s", DB_HOST, DB_PORT, DB_SCHEMA);
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
statement = connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testString() {
final String sql = "select * from actor limit 10";
try {
ResultSet rs = statement.executeQuery(sql);
// 展开结果集数据库
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("actor_id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Date lastUpdate = rs.getDate("last_update");
// 输出数据
logger.debug("actor_id: {}, first_name: {}, last_name: {}, last_update: {}", id, firstName, lastName,
lastUpdate.toLocalDate());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void testQuery() {
final String sql = "SELECT * FROM `user` LIMIT 10";
try {
ResultSet rs = statement.executeQuery(sql);
// 展开结果集数据库
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
String email = rs.getString("email");
// 输出数据
logger.info("id: {}, name: {}, age: {}, address: {}, email: {}", id, name, age, address, email);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,87 @@
package io.github.dunwu.javadb;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@Rollback
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpringBootDataJdbcApplication.class })
public class SpringBootDataJdbcTest {
private static final Logger log = LoggerFactory.getLogger(SpringBootDataJdbcTest.class);
@Autowired
private UserDao userDAO;
@Before
public void before() {
userDAO.truncate();
}
@Test
public void insert() {
userDAO.insert(new User("张三", 18, "北京", "user1@163.com"));
User linda = userDAO.queryByName("张三");
assertThat(linda).isNotNull();
}
@Test
public void batchInsert() {
List<User> users = new ArrayList<>();
users.add(new User("张三", 18, "北京", "user1@163.com"));
users.add(new User("李四", 19, "上海", "user1@163.com"));
users.add(new User("王五", 18, "南京", "user1@163.com"));
users.add(new User("赵六", 20, "武汉", "user1@163.com"));
userDAO.batchInsert(users);
int count = userDAO.count();
assertThat(count).isEqualTo(4);
List<User> list = userDAO.list();
assertThat(list).isNotEmpty().hasSize(4);
list.forEach(user -> {
log.info(user.toString());
});
}
@Test
public void delete() {
List<User> users = new ArrayList<>();
users.add(new User("张三", 18, "北京", "user1@163.com"));
users.add(new User("李四", 19, "上海", "user1@163.com"));
users.add(new User("王五", 18, "南京", "user1@163.com"));
users.add(new User("赵六", 20, "武汉", "user1@163.com"));
userDAO.batchInsert(users);
userDAO.deleteByName("张三");
User user = userDAO.queryByName("张三");
assertThat(user).isNull();
userDAO.deleteAll();
List<User> list = userDAO.list();
assertThat(list).isEmpty();
}
@Test
public void update() {
userDAO.insert(new User("张三", 18, "北京", "user1@163.com"));
User oldUser = userDAO.queryByName("张三");
oldUser.setName("张三丰");
userDAO.update(oldUser);
User newUser = userDAO.queryByName("张三丰");
assertThat(newUser).isNotNull();
}
}

View File

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!-- logback中一共有5种有效级别分别是TRACE、DEBUG、INFO、WARN、ERROR优先级依次从低到高 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="FILE_NAME" value="javadb" />
<!-- 将记录日志打印到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender begin -->
<appender name="ALL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 根据时间来制定滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.dir}/logs/${FILE_NAME}-all.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 根据文件大小来制定滚动策略 -->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>30MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender end -->
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="TRACE">
<appender-ref ref="ALL" />
</logger>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->
</configuration>

View File

@ -1,7 +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>
@ -14,11 +14,11 @@
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring.version>4.3.13.RELEASE</spring.version>
<spring.version>5.2.8.RELEASE</spring.version>
<logback.version>1.2.3</logback.version>
<jedis.version>2.9.0</jedis.version>
<redisson.version>3.7.2</redisson.version>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>

View File

@ -21,141 +21,141 @@ import java.util.Set;
*/
public class JedisDemoTest {
private static final String REDIS_HOST = "192.168.28.32";
private static final String REDIS_HOST = "192.168.28.32";
private static final int REDIS_PORT = 6379;
private static final int REDIS_PORT = 6379;
private static Jedis jedis = null;
private static Jedis jedis = null;
private static Logger logger = LoggerFactory.getLogger(JedisDemoTest.class);
private static Logger logger = LoggerFactory.getLogger(JedisDemoTest.class);
@BeforeClass
public static void beforeClass() {
// Jedis 有多种构造方法,这里选用最简单的一种情况
jedis = new Jedis(REDIS_HOST, REDIS_PORT);
@BeforeClass
public static void beforeClass() {
// Jedis 有多种构造方法,这里选用最简单的一种情况
jedis = new Jedis(REDIS_HOST, REDIS_PORT);
// 触发 ping 命令
try {
jedis.ping();
logger.debug("jedis 连接成功。");
} catch (JedisConnectionException e) {
e.printStackTrace();
}
}
// 触发 ping 命令
try {
jedis.ping();
logger.debug("jedis 连接成功。");
} catch (JedisConnectionException e) {
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
if (null != jedis) {
jedis.close();
logger.debug("jedis 关闭连接。");
}
}
@AfterClass
public static void afterClass() {
if (null != jedis) {
jedis.close();
logger.debug("jedis 关闭连接。");
}
}
/**
* string
*/
@Test
public void testString() {
final String key = "word";
final String value1 = "first";
final String value2 = "second";
/**
* string
*/
@Test
public void testString() {
final String key = "word";
final String value1 = "first";
final String value2 = "second";
// 新增 key
jedis.set(key, value1);
Assert.assertEquals(value1, jedis.get(key));
// 新增 key
jedis.set(key, value1);
Assert.assertEquals(value1, jedis.get(key));
// 修改 key
jedis.set(key, value2);
Assert.assertEquals(value2, jedis.get(key));
// 修改 key
jedis.set(key, value2);
Assert.assertEquals(value2, jedis.get(key));
Assert.assertEquals(true, jedis.exists(key));
Assert.assertEquals(true, jedis.exists(key));
// 删除 key
jedis.del(key);
Assert.assertEquals(null, jedis.get(key));
Assert.assertEquals(false, jedis.exists(key));
}
// 删除 key
jedis.del(key);
Assert.assertEquals(null, jedis.get(key));
Assert.assertEquals(false, jedis.exists(key));
}
/**
* byte[] string
*/
@Test
public void testBytes() {
final byte[] key = "word".getBytes();
final byte[] value1 = "first".getBytes();
final byte[] value2 = "second".getBytes();
/**
* byte[] string
*/
@Test
public void testBytes() {
final byte[] key = "word".getBytes();
final byte[] value1 = "first".getBytes();
final byte[] value2 = "second".getBytes();
// 新增 key
jedis.set(key, value1);
Assert.assertArrayEquals(value1, jedis.get(key));
// 新增 key
jedis.set(key, value1);
Assert.assertArrayEquals(value1, jedis.get(key));
// 修改 key
jedis.set(key, value2);
Assert.assertArrayEquals(value2, jedis.get(key));
// 修改 key
jedis.set(key, value2);
Assert.assertArrayEquals(value2, jedis.get(key));
// 删除 key
jedis.del(key);
Assert.assertArrayEquals(null, jedis.get(key));
}
// 删除 key
jedis.del(key);
Assert.assertArrayEquals(null, jedis.get(key));
}
/**
* Hash
*/
@Test
public void testHash() {
final String key = "zpkey";
final String field1 = "first";
final String value1 = "一";
final String value1_1 = "1";
final String field2 = "second";
final String value2 = "二";
/**
* Hash
*/
@Test
public void testHash() {
final String key = "zpkey";
final String field1 = "first";
final String value1 = "一";
final String value1_1 = "1";
final String field2 = "second";
final String value2 = "二";
// 新增 field
jedis.hset(key, field1, value1);
jedis.hset(key, field2, value2);
Assert.assertEquals(value1, jedis.hget(key, field1));
Assert.assertEquals(value2, jedis.hget(key, field2));
// 新增 field
jedis.hset(key, field1, value1);
jedis.hset(key, field2, value2);
Assert.assertEquals(value1, jedis.hget(key, field1));
Assert.assertEquals(value2, jedis.hget(key, field2));
// 修改 field
jedis.hset(key, field1, value1_1);
Assert.assertEquals(value1_1, jedis.hget(key, field1));
// 修改 field
jedis.hset(key, field1, value1_1);
Assert.assertEquals(value1_1, jedis.hget(key, field1));
jedis.hdel(key, field1, value1_1);
Assert.assertEquals(null, jedis.hget(key, field1));
jedis.hdel(key, field1, value1_1);
Assert.assertEquals(null, jedis.hget(key, field1));
Assert.assertEquals(false, jedis.hexists(key, field1));
Assert.assertEquals(true, jedis.hexists(key, field2));
Assert.assertEquals(false, jedis.hexists(key, field1));
Assert.assertEquals(true, jedis.hexists(key, field2));
Map<String, String> results = jedis.hgetAll(key);
Assert.assertEquals(1, results.size());
}
Map<String, String> results = jedis.hgetAll(key);
Assert.assertEquals(1, results.size());
}
/**
* set & get
*/
@Test
public void testList() {
final String key = "colors";
// 存储数据到列表中
jedis.lpush(key, "Red");
jedis.lpush(key, "Yellow");
jedis.lpush(key, "Blue");
Assert.assertEquals(3L, jedis.llen(key).longValue());
/**
* set & get
*/
@Test
public void testList() {
final String key = "colors";
// 存储数据到列表中
jedis.lpush(key, "Red");
jedis.lpush(key, "Yellow");
jedis.lpush(key, "Blue");
Assert.assertEquals(3L, jedis.llen(key).longValue());
// 获取存储的数据并输出
List<String> list = jedis.lrange("colors", 0, 2);
for (String aList : list) {
System.out.println("列表项为: " + aList);
}
}
// 获取存储的数据并输出
List<String> list = jedis.lrange("colors", 0, 2);
for (String aList : list) {
System.out.println("列表项为: " + aList);
}
}
@Test
public void testKeys() {
// 存储数据到列表中
Set<String> keys = jedis.keys("*");
for (String key : keys) {
System.out.println(key);
}
}
@Test
public void testKeys() {
// 存储数据到列表中
Set<String> keys = jedis.keys("*");
for (String key : keys) {
System.out.println(key);
}
}
}

View File

@ -18,55 +18,55 @@ import java.util.Set;
/**
* @author Zhang Peng
*/
@ActiveProfiles("test")
@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class JedisPoolDemoTest {
private static Logger logger = LoggerFactory.getLogger(JedisPoolDemoTest.class);
private static Logger logger = LoggerFactory.getLogger(JedisPoolDemoTest.class);
@Autowired
private JedisPool jedisPool;
@Autowired
private JedisPool jedisPool;
@Test
public void testSet() {
Jedis jedis = jedisPool.getResource();
jedis.set("first", "hello world");
System.out.println("first:" + jedis.get("first"));
logger.debug("first: {}", jedis.get("first"));
jedis.close();
}
@Test
public void testSet() {
Jedis jedis = jedisPool.getResource();
jedis.set("first", "hello world");
System.out.println("first:" + jedis.get("first"));
logger.debug("first: {}", jedis.get("first"));
jedis.close();
}
@Test
public void testLpush() {
Jedis jedis = jedisPool.getResource();
@Test
public void testLpush() {
Jedis jedis = jedisPool.getResource();
// 存储数据到列表中
jedis.lpush("colors", "Red");
jedis.lpush("colors", "Yellow");
jedis.lpush("colors", "Blue");
// 获取存储的数据并输出
List<String> list = jedis.lrange("colors", 0, 2);
for (int i = 0; i < list.size(); i++) {
System.out.println("列表项为: " + list.get(i));
}
// 存储数据到列表中
jedis.lpush("colors", "Red");
jedis.lpush("colors", "Yellow");
jedis.lpush("colors", "Blue");
// 获取存储的数据并输出
List<String> list = jedis.lrange("colors", 0, 2);
for (int i = 0; i < list.size(); i++) {
System.out.println("列表项为: " + list.get(i));
}
jedis.close();
}
jedis.close();
}
@Test
public void testKeys() {
Jedis jedis = jedisPool.getResource();
@Test
public void testKeys() {
Jedis jedis = jedisPool.getResource();
// 存储数据到列表中
Set<String> keys = jedis.keys("*");
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key);
}
// 存储数据到列表中
Set<String> keys = jedis.keys("*");
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key);
}
jedis.close();
}
jedis.close();
}
}

View File

@ -11,14 +11,14 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
*/
public class RedissonStandaloneTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:redisson-standalone.xml");
RedissonClient redisson = (RedissonClient) applicationContext.getBean("standalone");
// 首先获取redis中的key-value对象key不存在没关系
RBucket<String> keyObject = redisson.getBucket("key");
// 如果key存在就设置key的值为新值value
// 如果key不存在就设置key的值为value
keyObject.set("value");
}
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:redisson-standalone.xml");
RedissonClient redisson = (RedissonClient) applicationContext.getBean("standalone");
// 首先获取redis中的key-value对象key不存在没关系
RBucket<String> keyObject = redisson.getBucket("key");
// 如果key存在就设置key的值为新值value
// 如果key不存在就设置key的值为value
keyObject.set("value");
}
}

View File

@ -1,12 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="false">
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="false">
<description>Spring基础配置</description>
<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,20 +1,20 @@
<?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"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
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">
<!-- 开发环境配置文件 -->
<beans profile="dev">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/properties/application.properties,
<!-- 开发环境配置文件 -->
<beans profile="dev">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/properties/application.properties,
classpath*:/properties/application-dev.properties" />
</beans>
</beans>
<!-- 测试环境配置文件 -->
<beans profile="test">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/properties/application.properties,
<!-- 测试环境配置文件 -->
<beans profile="test">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/properties/application.properties,
classpath*:/properties/application-test.properties" />
</beans>
</beans>
</beans>

View File

@ -3,43 +3,43 @@
<!-- 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">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- 将记录日志打印到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender begin -->
<appender name="ALL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 根据时间来制定滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.dir}/logs/${FILE_NAME}.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- RollingFileAppender begin -->
<appender name="ALL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 根据时间来制定滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.dir}/logs/${FILE_NAME}.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 根据文件大小来制定滚动策略 -->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>30MB</maxFileSize>
</triggeringPolicy>
<!-- 根据文件大小来制定滚动策略 -->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>30MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender end -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender end -->
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="TRACE">
<appender-ref ref="ALL" />
</logger>
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="DEBUG">
<appender-ref ref="ALL" />
</logger>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->
</configuration>

View File

@ -1,21 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<description>redis configuration</description>
<description>redis configuration</description>
<!-- 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}" />
</bean>
<!-- 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}" />
</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}" />
</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}" />
</bean>
</beans>

View File

@ -1,21 +1,21 @@
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:redisson="http://redisson.org/schema/redisson"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
xmlns:redisson="http://redisson.org/schema/redisson"
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://redisson.org/schema/redisson
http://redisson.org/schema/redisson/redisson.xsd">
<bean id="stringCodec" class="org.redisson.client.codec.StringCodec" />
<redisson:client id="standalone"
name="aliasName1,aliasName2"
codec-ref="stringCodec">
<redisson:single-server address="redis://127.0.0.1:6379"
connection-pool-size="500"
idle-connection-timeout="10000"
connect-timeout="10000"
timeout="3000"
ping-timeout="30000"
reconnection-timeout="30000"
database="0" />
</redisson:client>
<bean id="stringCodec" class="org.redisson.client.codec.StringCodec" />
<redisson:client id="standalone"
name="aliasName1,aliasName2"
codec-ref="stringCodec">
<redisson:single-server address="redis://127.0.0.1:6379"
connection-pool-size="500"
idle-connection-timeout="10000"
connect-timeout="10000"
timeout="3000"
ping-timeout="30000"
reconnection-timeout="30000"
database="0" />
</redisson:client>
</beans>

View File

@ -26,7 +26,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>2.0.206</version>
</dependency>
<!-- db end -->
</dependencies>
@ -45,7 +45,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>2.0.206</version>
</dependency>
</dependencies>
</plugin>

View File

@ -16,7 +16,7 @@
<logback.version>1.2.3</logback.version>
<jedis.version>2.9.0</jedis.version>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>