findList() {
27 | return Flux.fromIterable(repository.findAll());
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/java/com/charles/api/controller/IndexController.java:
--------------------------------------------------------------------------------
1 | package com.charles.api.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.ui.Model;
5 | import org.springframework.web.bind.annotation.RequestMapping;
6 | import springfox.documentation.annotations.ApiIgnore;
7 |
8 | /**
9 | * Created by Jaycekon on 2018/1/14.
10 | */
11 | @ApiIgnore
12 | @Controller
13 | public class IndexController {
14 |
15 |
16 | @RequestMapping(value = "hello")
17 | public String index(Model model) {
18 | model.addAttribute("name", "黄伟杰");
19 | return "hello";
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/java/com/charles/api/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package com.charles.api.controller;
2 |
3 | import com.charles.business.mapper.UserMapper;
4 | import com.charles.business.model.User;
5 | import io.swagger.annotations.Api;
6 | import io.swagger.annotations.ApiImplicitParam;
7 | import io.swagger.annotations.ApiOperation;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 | import org.springframework.beans.factory.annotation.Autowired;
11 | import org.springframework.stereotype.Controller;
12 | import org.springframework.ui.Model;
13 | import org.springframework.web.bind.annotation.*;
14 | import org.springframework.web.servlet.ModelAndView;
15 | import springfox.documentation.annotations.ApiIgnore;
16 |
17 | import java.util.List;
18 |
19 | /**
20 | * 获取用户基本信息类,用于测试读写分离
21 | *
22 | * 2018/1/17 14:08
23 | */
24 | @RequestMapping("/users")
25 | @Api(tags = "用户数据API")
26 | @Controller
27 | public class UserController {
28 | private Logger logger = LoggerFactory.getLogger(UserController.class);
29 |
30 | @Autowired
31 | private UserMapper userMapper;
32 |
33 |
34 | @ApiOperation(value = "查找用户", notes = "根据 IdCard 获取用户")
35 | @RequestMapping(value = "/lists", method = RequestMethod.GET)
36 | @ResponseBody
37 | public User findByIdCard(String idCard) {
38 | User u = userMapper.selectByIdCard(idCard);
39 | logger.info("获取结果:{}", u);
40 | return u;
41 | }
42 |
43 |
44 | @ApiOperation(value = "保存用户", notes = "保存用户")
45 | @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
46 | @RequestMapping(value = "/save", method = RequestMethod.POST)
47 | public User saveUser(@RequestBody User user) {
48 | userMapper.insert(user);
49 | logger.info("保存结果:{}", user);
50 | return user;
51 | }
52 |
53 |
54 | @ApiIgnore
55 | @RequestMapping(value = "/list", method = RequestMethod.GET)
56 | public String list(Model model) {
57 | List users = userMapper.selectAll();
58 | model.addAttribute("users", users);
59 | model.addAttribute("title", "用户管理");
60 | return "user/list";
61 | }
62 |
63 | @ApiIgnore
64 | @RequestMapping(value = "/{id}", method = RequestMethod.GET)
65 | public String query(@PathVariable String id, Model model) {
66 | User user = userMapper.selectByPrimaryKey(Integer.valueOf(id));
67 | model.addAttribute("user", user);
68 | model.addAttribute("title", "查看用户");
69 | return "user/view";
70 | }
71 |
72 |
73 | @ApiIgnore
74 | @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
75 | public String saveOrUpdate(User user) {
76 | User temp = userMapper.selectByPrimaryKey(user.getId());
77 | if (temp == null) {
78 | userMapper.insert(user);
79 | } else {
80 | user.setId(temp.getId());
81 | userMapper.updateByPrimaryKeySelective(user);
82 | }
83 | return "redirect:list";
84 | }
85 |
86 |
87 | @ApiIgnore
88 | @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
89 | public ModelAndView delete(@PathVariable Integer id) {
90 | userMapper.deleteByPrimaryKey(id);
91 | return new ModelAndView("redirect:/users/list");
92 | }
93 |
94 |
95 | @ApiIgnore
96 | @RequestMapping(value = "modify/{id}")
97 | public String modify(@PathVariable Integer id, Model model) {
98 | User user = userMapper.selectByPrimaryKey(id);
99 | model.addAttribute("user", user);
100 | model.addAttribute("title", "修改用户");
101 | return "user/form";
102 | }
103 |
104 |
105 | @ApiIgnore
106 | @RequestMapping(value = "form")
107 | public String form(Model model) {
108 | model.addAttribute("user", new User());
109 | model.addAttribute("title", "创建用户");
110 | return "user/form";
111 | }
112 |
113 | }
114 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/java/com/charles/api/model/Charles.java:
--------------------------------------------------------------------------------
1 | package com.charles.api.model;
2 |
3 | /**
4 | * Created by Jaycekon on 2018/1/14.
5 | */
6 | public class Charles {
7 | private int id;
8 |
9 | private String name;
10 |
11 |
12 | public Charles(int id, String name) {
13 | this.id = id;
14 | this.name = name;
15 | }
16 |
17 | public int getId() {
18 | return id;
19 | }
20 |
21 | public void setId(int id) {
22 | this.id = id;
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public void setName(String name) {
30 | this.name = name;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/java/com/charles/api/repository/CharlesRepository.java:
--------------------------------------------------------------------------------
1 | package com.charles.api.repository;
2 |
3 | import com.charles.api.model.Charles;
4 | import org.springframework.stereotype.Repository;
5 |
6 | import java.util.Collection;
7 | import java.util.concurrent.ConcurrentHashMap;
8 | import java.util.concurrent.ConcurrentMap;
9 | import java.util.concurrent.atomic.AtomicInteger;
10 |
11 | /**
12 | * Created by Jaycekon on 2018/1/14.
13 | */
14 | @Repository
15 | public class CharlesRepository {
16 |
17 | private static final ConcurrentMap map = new ConcurrentHashMap<>();
18 |
19 | static {
20 | map.put(1, new Charles(1, "charles"));
21 | }
22 |
23 | private static AtomicInteger ID_CREATOR = new AtomicInteger(0);
24 |
25 |
26 | public Charles save(Charles charles) {
27 | int id = ID_CREATOR.incrementAndGet();
28 | charles.setId(id);
29 | map.put(id, charles);
30 | return charles;
31 |
32 | }
33 |
34 |
35 | public Collection findAll() {
36 | return map.values();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url=jdbc:mysql://localhost:3306/charles_blog
2 | spring.datasource.username=root
3 | spring.datasource.password=root
4 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
5 |
6 | #别名扫描目录
7 | mybatis.type-aliases-package=com.charles.business.model
8 | #Mapper.xml扫描目录
9 | mybatis.mapper-locations=classpath:mybatis-mappers/*.xml
10 |
11 |
12 | #tkmapper 帮助工具
13 | mapper.mappers=com.charles.business.MyMapper
14 | mapper.not-empty=false
15 | mapper.identity=MYSQL
16 |
17 | spring.thymeleaf.encoding=UTF-8
18 | spring.thymeleaf.cache=false
19 | spring.thymeleaf.mode=HTML5
20 |
21 |
22 | management.security.enable=false
23 |
24 |
25 | spring.datasource.master.jdbcurl=jdbc:mysql://localhost:3306/charles_blog
26 | spring.datasource.master.username=root
27 | spring.datasource.master.password=root
28 | spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver
29 |
30 |
31 | spring.datasource.slave.jdbcurl=jdbc:mysql://localhost:3306/charles_blog
32 | spring.datasource.slave.username=root
33 | spring.datasource.slave.password=root
34 | spring.datasource.slave.driver-class-name=com.mysql.jdbc.Driver
35 |
36 | spring.datasource.read = get,select,count,list,query
37 | spring.datasource.write = add,create,update,delete,remove,insert
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/static/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-api/src/main/resources/static/favicon.ico
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/templates/fragment/footer.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | Thymeleaf In Action
7 |
8 |
9 |
12 |
13 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/templates/fragment/header.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | Thymeleaf In Action
7 |
8 |
9 |
10 |
Spring-Blog Jayce
11 |
主页
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | hello
5 |
6 |
7 |
8 |
9 | 3333
10 |
11 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/templates/user/form.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | Thymeleaf In Action
7 |
8 |
9 |
10 | JayceKong
11 |
12 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/templates/user/list.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | Thymeleaf In Action
7 |
8 |
9 |
10 | JayceKong
11 |
14 |
15 |
16 |
17 | ID |
18 | username |
19 | idcard |
20 | phone |
21 | password |
22 |
23 |
24 |
25 |
26 | 没有用户信息! |
27 |
28 |
29 | |
30 | |
31 | |
32 | |
33 | |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/main/resources/templates/user/view.html:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | Thymeleaf In Action
7 |
8 |
9 | JayceKong
10 |
11 | ID:
12 | UserName:
13 | idCard:
14 | Phone:
15 | Password:
16 |
17 |
18 |
22 |
23 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/test/java/com/charles/api/SpringBlogApiApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.charles.api;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
9 | import org.springframework.boot.test.context.SpringBootTest;
10 | import org.springframework.test.context.junit4.SpringRunner;
11 |
12 | @RunWith(SpringRunner.class)
13 | @SpringBootTest
14 | public class SpringBlogApiApplicationTests {
15 |
16 | private static Logger logger = LoggerFactory.getLogger(SpringBlogApiApplicationTests.class);
17 |
18 | @Autowired
19 | private DataSourceProperties dataSourceProperties;
20 |
21 | @Test
22 | public void contextLoads() {
23 | logger.info("hello");
24 | logger.info(dataSourceProperties.getUrl());
25 | logger.info(dataSourceProperties.getUsername());
26 | logger.info("end");
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/Spring-Blog-api/src/test/java/com/charles/api/mapper/UserMapperTest.java:
--------------------------------------------------------------------------------
1 | package com.charles.api.mapper;
2 |
3 | import com.charles.business.mapper.UserMapper;
4 | import com.charles.business.model.User;
5 | import org.junit.Assert;
6 | import org.junit.Test;
7 | import org.junit.runner.RunWith;
8 | import org.mybatis.spring.annotation.MapperScan;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.boot.test.context.SpringBootTest;
11 | import org.springframework.test.annotation.Rollback;
12 | import org.springframework.test.context.junit4.SpringRunner;
13 | import org.springframework.transaction.annotation.Transactional;
14 |
15 | /**
16 | * Created by weijie_huang on 2017/9/7.
17 | */
18 |
19 | public class UserMapperTest {
20 | private UserMapper mapper;
21 |
22 |
23 | public void testInset() {
24 | User user = new User("Jaycekon","1234","1234","123");
25 | int i = mapper.insert(user);
26 | Assert.assertNotEquals(0, i);
27 | }
28 |
29 |
30 | public void testSelect(){
31 | User user = mapper.selectByIdCard("440182199512042311");
32 | Assert.assertNotNull(user);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Spring-Blog-business/build.gradle:
--------------------------------------------------------------------------------
1 | dependencies {
2 | compile project(":Spring-Blog-common")
3 |
4 | compile "tk.mybatis:mapper-spring-boot-starter:${tkMybatis}"
5 | compile "com.alibaba:fastjson:${fastjson}"
6 | compile "org.projectlombok:lombok:${lombok}"
7 | compile "com.fasterxml.jackson.core:jackson-core:${jackson}"
8 | testCompile group: 'junit', name: 'junit', version: '4.12'
9 | }
10 |
--------------------------------------------------------------------------------
/Spring-Blog-business/out/production/classes/com/charles/business/MyMapper.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-business/out/production/classes/com/charles/business/MyMapper.class
--------------------------------------------------------------------------------
/Spring-Blog-business/out/production/classes/com/charles/business/mapper/UserMapper.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-business/out/production/classes/com/charles/business/mapper/UserMapper.class
--------------------------------------------------------------------------------
/Spring-Blog-business/out/production/classes/com/charles/business/model/BaseEntity.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-business/out/production/classes/com/charles/business/model/BaseEntity.class
--------------------------------------------------------------------------------
/Spring-Blog-business/out/production/classes/com/charles/business/model/User.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-business/out/production/classes/com/charles/business/model/User.class
--------------------------------------------------------------------------------
/Spring-Blog-business/src/main/java/com/charles/business/MyMapper.java:
--------------------------------------------------------------------------------
1 | package com.charles.business;
2 |
3 | import tk.mybatis.mapper.common.Mapper;
4 | import tk.mybatis.mapper.common.MySqlMapper;
5 |
6 | /**
7 | * Created by weijie_huang on 2017/9/7.
8 | */
9 | public interface MyMapper extends Mapper, MySqlMapper {
10 | }
11 |
--------------------------------------------------------------------------------
/Spring-Blog-business/src/main/java/com/charles/business/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package com.charles.business.mapper;
2 |
3 | import com.charles.business.MyMapper;
4 | import com.charles.business.model.User;
5 | import org.apache.ibatis.annotations.Mapper;
6 | import org.apache.ibatis.annotations.Select;
7 |
8 | /**
9 | * 2018/1/9 16:58
10 | */
11 | @Mapper
12 | public interface UserMapper extends MyMapper {
13 |
14 | @Select("select * from user where username=#{username}")
15 | User selectByName(String username);
16 |
17 | User selectByIdCard(String idCard);
18 | }
19 |
--------------------------------------------------------------------------------
/Spring-Blog-business/src/main/java/com/charles/business/model/BaseEntity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The MIT License (MIT)
3 | *
4 | * Copyright (c) 2014-2016 abel533@gmail.com
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a copy
7 | * of this software and associated documentation files (the "Software"), to deal
8 | * in the Software without restriction, including without limitation the rights
9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 | * copies of the Software, and to permit persons to whom the Software is
11 | * furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 | * THE SOFTWARE.
23 | */
24 |
25 | package com.charles.business.model;
26 |
27 | import javax.persistence.*;
28 | import java.io.Serializable;
29 |
30 |
31 | public class BaseEntity implements Serializable {
32 | @Id
33 | @Column(name = "Id")
34 | @GeneratedValue(strategy = GenerationType.IDENTITY)
35 | private Integer id;
36 |
37 | @Transient
38 | private Integer page = 1;
39 |
40 | @Transient
41 | private Integer rows = 10;
42 |
43 | public Integer getId() {
44 | return id;
45 | }
46 |
47 | public void setId(Integer id) {
48 | this.id = id;
49 | }
50 |
51 | public Integer getPage() {
52 | return page;
53 | }
54 |
55 | public void setPage(Integer page) {
56 | this.page = page;
57 | }
58 |
59 | public Integer getRows() {
60 | return rows;
61 | }
62 |
63 | public void setRows(Integer rows) {
64 | this.rows = rows;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Spring-Blog-business/src/main/java/com/charles/business/model/User.java:
--------------------------------------------------------------------------------
1 | package com.charles.business.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 | import lombok.experimental.Accessors;
8 |
9 | import javax.persistence.Column;
10 |
11 | /**
12 | * Created by weijie_huang on 2017/9/7.
13 | */
14 |
15 | @Getter
16 | @Setter
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | @Accessors(chain = true)
20 | public class User extends BaseEntity {
21 |
22 | private String password;
23 |
24 | private String username;
25 |
26 | private String idCard;
27 |
28 | private String phone;
29 | }
30 |
--------------------------------------------------------------------------------
/Spring-Blog-business/src/main/resources/mybatis-config.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Spring-Blog-business/src/main/resources/mybatis-mappers/UserMapper.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | username,id_card,phone,password
14 |
15 |
16 |
24 |
25 |
--------------------------------------------------------------------------------
/Spring-Blog-common/build.gradle:
--------------------------------------------------------------------------------
1 |
2 | dependencies{
3 | testCompile group: 'junit', name: 'junit', version: '4.12'
4 | compile "commons-lang:commons-lang:${commonslang}"
5 | compile "ch.qos.logback:logback-classic:${logVersion}"
6 | compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
7 | }
8 |
--------------------------------------------------------------------------------
/Spring-Blog-common/out/production/classes/com/charles/common/util/DateUtils.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-common/out/production/classes/com/charles/common/util/DateUtils.class
--------------------------------------------------------------------------------
/Spring-Blog-common/out/test/classes/com/charles/common/util/DateUtilsTest.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jaycekon/Spring-Blog/bdb2bce01ca1b1b68cbf7f6b8b48181d72274bde/Spring-Blog-common/out/test/classes/com/charles/common/util/DateUtilsTest.class
--------------------------------------------------------------------------------
/Spring-Blog-common/src/main/java/com/charles/common/util/DateUtils.java:
--------------------------------------------------------------------------------
1 | package com.charles.common.util;
2 |
3 | import org.apache.commons.lang.StringUtils;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import java.text.ParseException;
8 | import java.text.SimpleDateFormat;
9 | import java.util.Calendar;
10 | import java.util.Date;
11 | import java.util.GregorianCalendar;
12 |
13 | /**
14 | * 日期操作类
15 | *
16 | */
17 | public class DateUtils {
18 |
19 | public static final String YYYYMMDD = "yyyy-MM-dd";
20 | public static final String YYYYMMDDS = "yyyyMMdd";
21 | public static final String YYYYMMDDHMS = "yyyy-MM-dd HH:mm:ss";
22 | public static final String YYYYMMDDHM = "yyyy-MM-dd HH:mm";
23 | private static Logger logger = LoggerFactory.getLogger(DateUtils.class);
24 | private static ThreadLocal threadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
25 |
26 | private DateUtils() {
27 | }
28 |
29 |
30 | public static String format(Date date) {
31 | return format(date, YYYYMMDD);
32 | }
33 |
34 |
35 | public static Date parse(String dateStr, String dateFormat) throws ParseException {
36 | threadLocal.get().applyPattern(dateFormat);
37 | return threadLocal.get().parse(dateStr);
38 | }
39 |
40 | /**
41 | * 将日期类型转换成指定格式的日期字符串
42 | *
43 | * @param date 待转换的日期
44 | * @param dateFormat 日期格式字符串
45 | * @return String
46 | */
47 | public static String format(Date date, String dateFormat) {
48 | if (StringUtils.isEmpty(dateFormat) || date == null) {
49 | threadLocal.get().applyPattern(YYYYMMDDHMS);
50 | return threadLocal.get().format(new Date());
51 | }
52 | threadLocal.get().applyPattern(dateFormat);
53 | return threadLocal.get().format(date);
54 | }
55 |
56 | /**
57 | * 将指定格式的字符串转换成日期类型
58 | *
59 | * @param dateStr 待转换的日期字符串
60 | * @param dateFormat 日期格式字符串
61 | * @return Date
62 | */
63 | public static Date toDate(String dateStr, String dateFormat) {
64 | if (dateStr == null || "".equals(dateStr)) {
65 | return null;
66 | }
67 | try {
68 | return parse(dateStr, dateFormat);
69 | } catch (Exception e) {
70 | logger.error("error in toDate :{}", e);
71 | }
72 | return null;
73 | }
74 |
75 | public static Date toDate(String str) {
76 | if (StringUtils.isEmpty(str)) {
77 | return toDate("1900-01-01", YYYYMMDD);
78 | }
79 | return toDate(str, YYYYMMDD);
80 | }
81 |
82 | public static Date toDate2(String str) {
83 | String dateFormat = YYYYMMDD;
84 | // 2012-01-01 00:00:00格式
85 | if (str.matches("\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}")) {
86 | dateFormat = YYYYMMDDHMS;
87 | // 2012-01-01 00:00格式
88 | } else if (str.matches("\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}")) {
89 | dateFormat = YYYYMMDDHM;
90 | }
91 | return toDate(str, dateFormat);
92 | }
93 |
94 | /**
95 | * 根据指定年度和月份获取月初日期
96 | *
97 | * @param year
98 | * @param month
99 | * @return
100 | */
101 | public static Date getFirstDayOfMonth(int year, int month) {
102 |
103 | Calendar calendar = Calendar.getInstance();
104 | calendar.set(Calendar.YEAR, year);
105 | calendar.set(Calendar.MONTH, month - 1);
106 | calendar.set(Calendar.DATE, 1);
107 | calendar.set(Calendar.HOUR_OF_DAY, 0);
108 | calendar.set(Calendar.MINUTE, 0);
109 | calendar.set(Calendar.SECOND, 0);
110 | calendar.set(Calendar.MILLISECOND, 0);
111 |
112 | return calendar.getTime();
113 | }
114 |
115 | /**
116 | * 根据指定年度和月份获取月初日期
117 | *
118 | * @param yearMonth
119 | * @return
120 | */
121 | public static Date getFirstDayOfMonth(String yearMonth) {
122 | int year = Integer.parseInt(yearMonth.substring(0, 4));
123 | int month = Integer.parseInt(yearMonth.substring(4, yearMonth.length()));
124 | Calendar calendar = Calendar.getInstance();
125 | calendar.set(Calendar.YEAR, year);
126 | calendar.set(Calendar.MONTH, month - 1);
127 | calendar.set(Calendar.DATE, 1);
128 | calendar.set(Calendar.HOUR_OF_DAY, 0);
129 | calendar.set(Calendar.MINUTE, 0);
130 | calendar.set(Calendar.SECOND, 0);
131 | calendar.set(Calendar.MILLISECOND, 0);
132 |
133 | return calendar.getTime();
134 | }
135 |
136 | /**
137 | * 根据指定年度和月份获取月末日期
138 | *
139 | * @param yearMonth
140 | * @return
141 | */
142 | public static Date getLastDayOfMonth(String yearMonth) {
143 | int year = Integer.parseInt(yearMonth.substring(0, 4));
144 | int month = Integer.parseInt(yearMonth.substring(4, yearMonth.length()));
145 | Calendar calendar = Calendar.getInstance();
146 | calendar.set(Calendar.YEAR, year);
147 | calendar.set(Calendar.MONTH, month - 1);
148 | calendar.set(Calendar.DATE, 1);
149 |
150 | int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
151 |
152 | calendar.set(Calendar.DAY_OF_MONTH, maxDay);
153 | calendar.set(Calendar.HOUR_OF_DAY, 0);
154 | calendar.set(Calendar.MINUTE, 0);
155 | calendar.set(Calendar.SECOND, 0);
156 | calendar.set(Calendar.MILLISECOND, 0);
157 |
158 | return calendar.getTime();
159 | }
160 |
161 | /**
162 | * 根据指定年度和月份获取月末日期
163 | *
164 | * @param year
165 | * @param month
166 | * @return
167 | */
168 | public static Date getLastDayOfMonth(int year, int month) {
169 |
170 | Calendar calendar = Calendar.getInstance();
171 | calendar.set(Calendar.YEAR, year);
172 | calendar.set(Calendar.MONTH, month - 1);
173 | calendar.set(Calendar.DATE, 1);
174 |
175 | int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
176 |
177 | calendar.set(Calendar.DAY_OF_MONTH, maxDay);
178 | calendar.set(Calendar.HOUR_OF_DAY, 0);
179 | calendar.set(Calendar.MINUTE, 0);
180 | calendar.set(Calendar.SECOND, 0);
181 | calendar.set(Calendar.MILLISECOND, 0);
182 |
183 | return calendar.getTime();
184 | }
185 |
186 | public static Date getFirstDateOfThisYear() {
187 | Calendar ca = Calendar.getInstance();
188 | ca.set(Calendar.MONTH, 0);
189 | ca.set(Calendar.DATE, 1);
190 | ca.set(Calendar.HOUR_OF_DAY, 0);
191 | ca.set(Calendar.MINUTE, 0);
192 | ca.set(Calendar.SECOND, 0);
193 | ca.set(Calendar.MILLISECOND, 0);
194 | return ca.getTime();
195 | }
196 |
197 |
198 | /**
199 | * 获取指定日期的月
200 | *
201 | * @param date
202 | * @return
203 | */
204 | public static int getMonthOfDate(Date date) {
205 | if (date == null) {
206 | throw new IllegalArgumentException("Invalid argument, date is null in getMonthOfDate");
207 | }
208 | Calendar c = Calendar.getInstance();
209 | c.setTime(date);
210 | return c.get(Calendar.MONTH) + 1;
211 | }
212 |
213 | /**
214 | * 获取指定日期的季度
215 | *
216 | * @param date
217 | * @return
218 | */
219 | public static int getQuarterOfDate(Date date) {
220 | if (date == null) {
221 | throw new IllegalArgumentException("Invalid argument, date is null in getQuarterOfDate");
222 | }
223 | Calendar c = Calendar.getInstance();
224 | c.setTime(date);
225 | int month = c.get(Calendar.MONTH) + 1;
226 | return getQuarter(month);
227 |
228 | }
229 |
230 | private static int getQuarter(int month) {
231 | int quarter = 1;
232 | if (month >= 1 && month <= 3) {
233 | quarter = 1;
234 | }
235 | if (month >= 4 && month <= 6) {
236 | quarter = 2;
237 | }
238 | if (month >= 7 && month <= 9) {
239 | quarter = 3;
240 | }
241 | if (month >= 10 && month <= 12) {
242 | quarter = 4;
243 | }
244 | return quarter;
245 | }
246 |
247 | /**
248 | * 获取指定日期所在月份的最后一天
249 | *
250 | * @param date
251 | * @return
252 | */
253 | public static Date getLastDayOfMonth(Date date) {
254 |
255 | if (date == null) {
256 | throw new IllegalArgumentException("Invalid argument, date is null");
257 | }
258 |
259 | Calendar calendar1 = Calendar.getInstance();
260 | calendar1.setTime(date);
261 | int maxDay = calendar1.getActualMaximum(Calendar.DAY_OF_MONTH);
262 |
263 | calendar1.set(Calendar.DAY_OF_MONTH, maxDay);
264 | calendar1.set(Calendar.HOUR_OF_DAY, 0);
265 | calendar1.set(Calendar.MINUTE, 0);
266 | calendar1.set(Calendar.SECOND, 0);
267 | calendar1.set(Calendar.MILLISECOND, 0);
268 |
269 | return calendar1.getTime();
270 | }
271 |
272 | /**
273 | * 获取指定日期所在月份的第一天
274 | *
275 | * @param date
276 | * @return
277 | */
278 | public static Date getFirstDayOfMonth(Date date) {
279 |
280 | if (date == null) {
281 | throw new IllegalArgumentException("Invalid argument, date is null");
282 | }
283 |
284 | Calendar calendar1 = Calendar.getInstance();
285 | calendar1.setTime(date);
286 | calendar1.set(Calendar.DAY_OF_MONTH, 1);
287 | calendar1.set(Calendar.HOUR_OF_DAY, 0);
288 | calendar1.set(Calendar.MINUTE, 0);
289 | calendar1.set(Calendar.SECOND, 0);
290 | calendar1.set(Calendar.MILLISECOND, 0);
291 |
292 | return calendar1.getTime();
293 | }
294 |
295 |
296 | /**
297 | * 比较两个日期之间的天数差异,例如:如果left比right晚一天,返回1,如果相等返回0, 如果left比right早一天,返回-1
298 | *
299 | * @param left
300 | * @param right
301 | * @return int 差异天数
302 | */
303 | public static int getDiffDays(Date left, Date right) {
304 | GregorianCalendar leftCaldr = new GregorianCalendar();
305 | GregorianCalendar rightCaldr = new GregorianCalendar();
306 | leftCaldr.setTime(left);
307 | rightCaldr.setTime(right);
308 |
309 | leftCaldr.set(GregorianCalendar.HOUR_OF_DAY, 0);
310 | leftCaldr.set(GregorianCalendar.MINUTE, 0);
311 | leftCaldr.set(GregorianCalendar.SECOND, 0);
312 | leftCaldr.set(GregorianCalendar.MILLISECOND, 0);
313 |
314 | rightCaldr.set(GregorianCalendar.HOUR_OF_DAY, 0);
315 | rightCaldr.set(GregorianCalendar.MINUTE, 0);
316 | rightCaldr.set(GregorianCalendar.SECOND, 0);
317 | rightCaldr.set(GregorianCalendar.MILLISECOND, 0);
318 |
319 | long leftMilSec = leftCaldr.getTimeInMillis();
320 | long rightMilSec = rightCaldr.getTimeInMillis();
321 |
322 | long res = (leftMilSec - rightMilSec) / (24L * 60L * 60L * 1000L);
323 |
324 | return (int) res;
325 | }
326 |
327 |
328 | /**
329 | * 得到相差offset天的时间
330 | *
331 | * @param date
332 | * @param offset
333 | * @return
334 | */
335 | public static Date getDateByOffset(Date date, int offset) {
336 | Calendar cal = Calendar.getInstance();
337 | cal.setTime(date);
338 | cal.add(Calendar.DAY_OF_YEAR, offset);
339 | return cal.getTime();
340 | }
341 |
342 | public static final int getDayOfWeek(Date date) {
343 | Calendar calendar = GregorianCalendar.getInstance();
344 | calendar.setTime(date);
345 | return calendar.get(Calendar.DAY_OF_WEEK);
346 | }
347 |
348 | public static Date clearTime(Date date) {
349 | if (date == null) {
350 | return null;
351 | }
352 |
353 | Calendar c = Calendar.getInstance();
354 | c.setTime(date);
355 | c.set(Calendar.HOUR_OF_DAY, 0);
356 | c.set(Calendar.MINUTE, 0);
357 | c.set(Calendar.SECOND, 0);
358 | c.set(Calendar.MILLISECOND, 0);
359 |
360 | return c.getTime();
361 | }
362 |
363 | /**
364 | * getDateDiffDays
365 | *
366 | * @param curDate
367 | * @param oriDate
368 | * @return int
369 | * @author henry_li
370 | * @since 2006-12-28
371 | */
372 | public static int getDateDiffDays(Date curDate, Date oriDate) {
373 | return Math.abs(getDateDiffDay(curDate, oriDate));
374 | }
375 |
376 | /**
377 | * 计算时间差,>0表示当前开始日期为明天, <0表示当前开始日期是昨天
378 | *
379 | * @param curDate
380 | * @param oriDate
381 | * @return
382 | */
383 | public static int getDateDiffDay(Date curDate, Date oriDate) {
384 | final int msPerDay = 1000 * 60 * 60 * 24;
385 | Date startDate = new Date();
386 | Date endDate = new Date();
387 |
388 | try {
389 | startDate = new SimpleDateFormat(YYYYMMDD).parse(getDate(curDate));
390 | endDate = new SimpleDateFormat(YYYYMMDD).parse(getDate(oriDate));
391 | } catch (ParseException ex) {
392 | logger.error("error in getDateDiffDay:{}", ex);
393 | }
394 |
395 | return (int) (startDate.getTime() - endDate.getTime()) / msPerDay;
396 | }
397 |
398 | public static String getDate(Date date) {
399 | return getDate(date, YYYYMMDD);
400 | }
401 |
402 | /**
403 | * @param date
404 | * @param pattern
405 | * @return
406 | */
407 | public static String getDate(Date date, String pattern) {
408 | return new SimpleDateFormat(pattern).format(date);
409 | }
410 |
411 | /**
412 | * 得到相差offset月的时间
413 | *
414 | * @param date
415 | * @param offset
416 | * @return
417 | */
418 | public static Date getMonthByOffset(Date date, int offset) {
419 | Calendar cal = Calendar.getInstance();
420 | cal.setTime(date);
421 | cal.add(Calendar.MONTH, offset);
422 | return cal.getTime();
423 | }
424 |
425 | public static boolean isBetween(Date beginDate, Date endDate, Date date) {
426 | int offsetAll = getDiffDays(endDate, beginDate);
427 | int offsetBegin = getDiffDays(date, beginDate);
428 | int offsetEnd = getDiffDays(endDate, date);
429 | return offsetBegin <= offsetAll && offsetEnd <= offsetAll;
430 | }
431 |
432 | /**
433 | * 将long类型转化为Date
434 | *
435 | * @param l long
436 | * @return date
437 | * @throws ParseException
438 | */
439 | public static Date longToDate(long l) {
440 | return new Date(l * 1000);
441 | }
442 | }
443 |
--------------------------------------------------------------------------------
/Spring-Blog-common/src/test/java/com/charles/common/util/DateUtilsTest.java:
--------------------------------------------------------------------------------
1 | package com.charles.common.util;
2 |
3 | import org.junit.Test;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import java.util.Date;
8 |
9 | /**
10 | * 2018/1/9 16:34
11 | */
12 | public class DateUtilsTest {
13 |
14 | private static Logger logger = LoggerFactory.getLogger(DateUtilsTest.class);
15 |
16 | @Test
17 | public void testDateUtils() {
18 | String date = DateUtils.format(new Date());
19 | logger.info("DateUtils测试类 运行结果:{}",date);
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | /build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 |
5 | ### STS ###
6 | .apt_generated
7 | .classpath
8 | .factorypath
9 | .project
10 | .settings
11 | .springBeans
12 |
13 | ### IntelliJ IDEA ###
14 | .idea
15 | *.iws
16 | *.iml
17 | *.ipr
18 |
19 | ### NetBeans ###
20 | nbproject/private/
21 | build/
22 | nbbuild/
23 | dist/
24 | nbdist/
25 | .nb-gradle/
--------------------------------------------------------------------------------
/Spring-Blog-webflux/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext {
3 | springBootVersion = '2.0.0.M7'
4 | }
5 | repositories {
6 | mavenCentral()
7 | maven { url "https://repo.spring.io/snapshot" }
8 | maven { url "https://repo.spring.io/milestone" }
9 | }
10 | dependencies {
11 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
12 | }
13 | }
14 |
15 | apply plugin: 'idea'
16 | apply plugin: 'org.springframework.boot'
17 | apply plugin: 'io.spring.dependency-management'
18 |
19 |
20 | repositories {
21 | maven {url "http://maven.aliyun.com/nexus/content/groups/public/"}
22 | mavenCentral()
23 | maven { url "https://repo.spring.io/snapshot" }
24 | maven { url "https://repo.spring.io/milestone" }
25 | }
26 |
27 |
28 | dependencies {
29 | compile project(":Spring-Blog-business")
30 | compile('org.springframework.boot:spring-boot-starter-webflux')
31 | runtime('org.springframework.boot:spring-boot-devtools')
32 | compile('org.springframework.boot:spring-boot-starter-data-redis')
33 | compile('org.springframework.boot:spring-boot-starter-actuator')
34 |
35 |
36 | compileOnly('org.projectlombok:lombok')
37 | runtime('mysql:mysql-connector-java')
38 | testCompile('org.springframework.boot:spring-boot-starter-test')
39 | testCompile('io.projectreactor:reactor-test')
40 | }
41 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/src/main/java/com/charles/webflux/WebfluxApplication.java:
--------------------------------------------------------------------------------
1 | package com.charles.webflux;
2 |
3 | import org.mybatis.spring.annotation.MapperScan;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 |
7 | @SpringBootApplication
8 | @MapperScan("com.charles.business.mapper")
9 | public class WebfluxApplication {
10 |
11 | public static void main(String[] args) {
12 | SpringApplication.run(WebfluxApplication.class, args);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/src/main/java/com/charles/webflux/congifuration/HelloWorldConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.charles.webflux.congifuration;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.web.reactive.function.server.*;
6 |
7 | import static org.springframework.web.reactive.function.BodyInserters.fromObject;
8 | import static org.springframework.web.reactive.function.server.RouterFunctions.route;
9 |
10 | /**
11 | * 2018/1/15 9:56
12 | */
13 | @Configuration
14 | public class HelloWorldConfiguration {
15 |
16 |
17 | @Bean
18 | public RouterFunction helloworld(){
19 | RequestPredicate requestPredicate = RequestPredicates.GET("/charles");
20 | HandlerFunction handlerFunction =
21 | request -> ServerResponse.ok().body(fromObject("Hello World"));
22 |
23 |
24 | return route(requestPredicate, handlerFunction);
25 |
26 | }
27 |
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/src/main/java/com/charles/webflux/controller/IndexController.java:
--------------------------------------------------------------------------------
1 | package com.charles.webflux.controller;
2 |
3 | import org.springframework.stereotype.Controller;
4 | import org.springframework.ui.ModelMap;
5 | import org.springframework.web.bind.annotation.GetMapping;
6 |
7 | /**
8 | * Created by Jaycekon on 2018/1/10.
9 | */
10 | @Controller
11 | public class IndexController {
12 |
13 | @GetMapping("index")
14 | public String index(ModelMap map) {
15 | map.addAttribute("host", "http://blog.didispace.com");
16 | return "index";
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/src/main/java/com/charles/webflux/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package com.charles.webflux.controller;
2 |
3 | import com.charles.business.model.User;
4 | import com.charles.webflux.services.UserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.PostMapping;
7 | import org.springframework.web.bind.annotation.RequestBody;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | /**
12 | * Created by Jaycekon on 2018/1/10.
13 | */
14 | @RestController
15 | @RequestMapping("/user")
16 | public class UserController {
17 | @Autowired
18 | private UserService userService;
19 |
20 |
21 | @PostMapping(value = "/save")
22 | public Object save(@RequestBody User user) {
23 | userService.saveOrUpdate(user);
24 | return user;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/src/main/java/com/charles/webflux/crawler/WebClientCrawler.java:
--------------------------------------------------------------------------------
1 | package com.charles.webflux.crawler;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.web.reactive.function.client.WebClient;
7 | import reactor.core.publisher.Mono;
8 |
9 | /**
10 | * TODO 加点注释
11 | *
12 | * @author weijie_huang
13 | * 2018/1/22 21:20
14 | */
15 | public class WebClientCrawler {
16 |
17 |
18 | private static Logger logger = LoggerFactory.getLogger(WebClientCrawler.class);
19 |
20 | public static void main(String[] args) {
21 | crawlClient();
22 | }
23 |
24 |
25 | /**
26 | * 抓取百度首页,直接输出结果
27 | */
28 | private static void crawlIndex() {
29 | Mono resp = WebClient.create()
30 | .method(HttpMethod.GET)
31 | .uri("http://www.baidu.com/")
32 | .retrieve()
33 | .bodyToMono(String.class);
34 |
35 | logger.info("抓取结果:{}", resp.block());
36 |
37 | }
38 |
39 | private static void crawlClient() {
40 | WebClient webClient = WebClient.create();
41 | Mono resp = webClient
42 | .method(HttpMethod.GET)
43 | .uri("http://www.baidu.com/")
44 | .retrieve()
45 | .bodyToMono(String.class);
46 |
47 | logger.info("抓取结果:{}", resp.block());
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/Spring-Blog-webflux/src/main/java/com/charles/webflux/nosql/RedisComponent.java:
--------------------------------------------------------------------------------
1 | package com.charles.webflux.nosql;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.data.redis.core.RedisTemplate;
8 | import org.springframework.data.redis.core.StringRedisTemplate;
9 | import org.springframework.data.redis.core.ValueOperations;
10 | import org.springframework.stereotype.Component;
11 |
12 | /**
13 | * Redis工具类
14 | * Created by Administrator on 2017/8/8.
15 | */
16 | @Component
17 | public class RedisComponent {
18 | @Autowired
19 | //操作字符串的template,StringRedisTemplate是RedisTemplate的一个子集
20 | private StringRedisTemplate stringRedisTemplate;
21 |
22 | private Logger logger = LoggerFactory.getLogger(RedisComponent.class);
23 |
24 | @Autowired
25 | // RedisTemplate,可以进行所有的操作
26 | private RedisTemplate