addressEnumeration = ni.getInetAddresses();
60 | while (addressEnumeration.hasMoreElements()) {
61 | InetAddress address = addressEnumeration.nextElement();
62 |
63 | // ignores all invalidated addresses
64 | if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) {
65 | continue;
66 | }
67 |
68 | return address;
69 | }
70 | }
71 |
72 | throw new RuntimeException("No validated local address!");
73 | }
74 |
75 | /**
76 | * Retrieve local address
77 | *
78 | * @return the string local address
79 | */
80 | public static String getLocalAddress() {
81 | return localAddress.getHostAddress();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/utils/PaddedAtomicLong.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.utils;
17 |
18 | import java.util.concurrent.atomic.AtomicLong;
19 |
20 | /**
21 | * Represents a padded {@link AtomicLong} to prevent the FalseSharing problem
22 | *
23 | * The CPU cache line commonly be 64 bytes, here is a sample of cache line after padding:
24 | * 64 bytes = 8 bytes (object reference) + 6 * 8 bytes (padded long) + 8 bytes (a long value)
25 | *
26 | * @author yutianbao
27 | */
28 | public class PaddedAtomicLong extends AtomicLong {
29 | private static final long serialVersionUID = -3415778863941386253L;
30 |
31 | /** Padded 6 long (48 bytes) */
32 | public volatile long p1, p2, p3, p4, p5, p6 = 7L;
33 |
34 | /**
35 | * Constructors from {@link AtomicLong}
36 | */
37 | public PaddedAtomicLong() {
38 | super();
39 | }
40 |
41 | public PaddedAtomicLong(long initialValue) {
42 | super(initialValue);
43 | }
44 |
45 | /**
46 | * To prevent GC optimizations for cleaning unused padded references
47 | */
48 | public long sumPaddingToPreventOptimization() {
49 | return p1 + p2 + p3 + p4 + p5 + p6;
50 | }
51 |
52 | }
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/utils/ValuedEnum.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.utils;
17 |
18 | /**
19 | * {@code ValuedEnum} defines an enumeration which is bounded to a value, you
20 | * may implements this interface when you defines such kind of enumeration, that
21 | * you can use {@link EnumUtils} to simplify parse and valueOf operation.
22 | *
23 | * @author yutianbao
24 | */
25 | public interface ValuedEnum {
26 | T value();
27 | }
28 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/worker/DisposableWorkerIdAssigner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker;
17 |
18 | import com.baidu.fsg.uid.utils.DockerUtils;
19 | import com.baidu.fsg.uid.utils.NetUtils;
20 | import com.baidu.fsg.uid.worker.dao.WorkerNodeDAO;
21 | import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity;
22 | import org.apache.commons.lang.math.RandomUtils;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 | import org.springframework.transaction.annotation.Transactional;
26 |
27 | import javax.annotation.Resource;
28 |
29 | /**
30 | * Represents an implementation of {@link WorkerIdAssigner},
31 | * the worker id will be discarded after assigned to the UidGenerator
32 | *
33 | * @author yutianbao
34 | */
35 | public class DisposableWorkerIdAssigner implements WorkerIdAssigner {
36 | private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);
37 |
38 | @Resource
39 | private WorkerNodeDAO workerNodeDAO;
40 |
41 | /**
42 | * Assign worker id base on database.
43 | * If there is host name & port in the environment, we considered that the node runs in Docker container
44 | * Otherwise, the node runs on an actual machine.
45 | *
46 | * @return assigned worker id
47 | */
48 | @Transactional
49 | public long assignWorkerId() {
50 | // build worker node entity
51 | WorkerNodeEntity workerNodeEntity = buildWorkerNode();
52 |
53 | // add worker node for new (ignore the same IP + PORT)
54 | workerNodeDAO.addWorkerNode(workerNodeEntity);
55 | LOGGER.info("Add worker node:" + workerNodeEntity);
56 |
57 | return workerNodeEntity.getId();
58 | }
59 |
60 | /**
61 | * Build worker node entity by IP and PORT
62 | */
63 | private WorkerNodeEntity buildWorkerNode() {
64 | WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
65 | if (DockerUtils.isDocker()) {
66 | workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
67 | workerNodeEntity.setHostName(DockerUtils.getDockerHost());
68 | workerNodeEntity.setPort(DockerUtils.getDockerPort());
69 |
70 | } else {
71 | workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
72 | workerNodeEntity.setHostName(NetUtils.getLocalAddress());
73 | workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
74 | }
75 |
76 | return workerNodeEntity;
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/worker/WorkerIdAssigner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker;
17 |
18 | /**
19 | * Represents a worker id assigner for {@link com.baidu.fsg.uid.impl.DefaultUidGenerator}
20 | *
21 | * @author yutianbao
22 | */
23 | public interface WorkerIdAssigner {
24 |
25 | /**
26 | * Assign worker id for {@link com.baidu.fsg.uid.impl.DefaultUidGenerator}
27 | *
28 | * @return assigned worker id
29 | */
30 | long assignWorkerId();
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/worker/WorkerNodeType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker;
17 |
18 | import com.baidu.fsg.uid.utils.ValuedEnum;
19 |
20 | /**
21 | * WorkerNodeType
22 | *
CONTAINER: Such as Docker
23 | * ACTUAL: Actual machine
24 | *
25 | * @author yutianbao
26 | */
27 | public enum WorkerNodeType implements ValuedEnum {
28 |
29 | CONTAINER(1), ACTUAL(2);
30 |
31 | /**
32 | * Lock type
33 | */
34 | private final Integer type;
35 |
36 | /**
37 | * Constructor with field of type
38 | */
39 | private WorkerNodeType(Integer type) {
40 | this.type = type;
41 | }
42 |
43 | @Override
44 | public Integer value() {
45 | return type;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/worker/dao/WorkerNodeDAO.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker.dao;
17 |
18 | import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity;
19 | import org.apache.ibatis.annotations.Param;
20 | import org.springframework.stereotype.Repository;
21 |
22 | /**
23 | * DAO for M_WORKER_NODE
24 | *
25 | * @author yutianbao
26 | */
27 | @Repository
28 | public interface WorkerNodeDAO {
29 |
30 | /**
31 | * Get {@link WorkerNodeEntity} by node host
32 | *
33 | * @param host
34 | * @param port
35 | * @return
36 | */
37 | WorkerNodeEntity getWorkerNodeByHostPort(@Param("host") String host, @Param("port") String port);
38 |
39 | /**
40 | * Add {@link WorkerNodeEntity}
41 | *
42 | * @param workerNodeEntity
43 | */
44 | void addWorkerNode(WorkerNodeEntity workerNodeEntity);
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/java/com/baidu/fsg/uid/worker/entity/WorkerNodeEntity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker.entity;
17 |
18 | import java.util.Date;
19 |
20 | import org.apache.commons.lang.builder.ReflectionToStringBuilder;
21 | import org.apache.commons.lang.builder.ToStringStyle;
22 |
23 | import com.baidu.fsg.uid.worker.WorkerNodeType;
24 |
25 | /**
26 | * Entity for M_WORKER_NODE
27 | *
28 | * @author yutianbao
29 | */
30 | public class WorkerNodeEntity {
31 |
32 | /**
33 | * Entity unique id (table unique)
34 | */
35 | private long id;
36 |
37 | /**
38 | * Type of CONTAINER: HostName, ACTUAL : IP.
39 | */
40 | private String hostName;
41 |
42 | /**
43 | * Type of CONTAINER: Port, ACTUAL : Timestamp + Random(0-10000)
44 | */
45 | private String port;
46 |
47 | /**
48 | * type of {@link WorkerNodeType}
49 | */
50 | private int type;
51 |
52 | /**
53 | * Worker launch date, default now
54 | */
55 | private Date launchDate = new Date();
56 |
57 | /**
58 | * Created time
59 | */
60 | private Date created;
61 |
62 | /**
63 | * Last modified
64 | */
65 | private Date modified;
66 |
67 | /**
68 | * Getters & Setters
69 | */
70 | public long getId() {
71 | return id;
72 | }
73 |
74 | public void setId(long id) {
75 | this.id = id;
76 | }
77 |
78 | public String getHostName() {
79 | return hostName;
80 | }
81 |
82 | public void setHostName(String hostName) {
83 | this.hostName = hostName;
84 | }
85 |
86 | public String getPort() {
87 | return port;
88 | }
89 |
90 | public void setPort(String port) {
91 | this.port = port;
92 | }
93 |
94 | public int getType() {
95 | return type;
96 | }
97 |
98 | public void setType(int type) {
99 | this.type = type;
100 | }
101 |
102 | public Date getLaunchDate() {
103 | return launchDate;
104 | }
105 |
106 | public void setLaunchDateDate(Date launchDate) {
107 | this.launchDate = launchDate;
108 | }
109 |
110 | public Date getCreated() {
111 | return created;
112 | }
113 |
114 | public void setCreated(Date created) {
115 | this.created = created;
116 | }
117 |
118 | public Date getModified() {
119 | return modified;
120 | }
121 |
122 | public void setModified(Date modified) {
123 | this.modified = modified;
124 | }
125 |
126 | @Override
127 | public String toString() {
128 | return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
129 | }
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/resources/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/id-spring-boot-starter/src/main/resources/.DS_Store
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/resources/META-INF/spring.factories:
--------------------------------------------------------------------------------
1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
2 | com.baidu.fsg.uid.config.UIDConfig,\
3 | com.baidu.fsg.uid.service.UidGenService
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/resources/config/cached-uid-spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/id-spring-boot-starter/src/main/resources/mapper/WORKER_NODE.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
17 | INSERT INTO WORKER_NODE
18 | (HOST_NAME,
19 | PORT,
20 | TYPE,
21 | LAUNCH_DATE,
22 | MODIFIED,
23 | CREATED)
24 | VALUES (
25 | #{hostName},
26 | #{port},
27 | #{type},
28 | #{launchDate},
29 | NOW(),
30 | NOW())
31 |
32 |
33 |
34 | SELECT
35 | ID,
36 | HOST_NAME,
37 | PORT,
38 | TYPE,
39 | LAUNCH_DATE,
40 | MODIFIED,
41 | CREATED
42 | FROM
43 | WORKER_NODE
44 | WHERE
45 | HOST_NAME = #{host} AND PORT = #{port}
46 |
47 |
--------------------------------------------------------------------------------
/kotlin_with_springbt/build.gradle:
--------------------------------------------------------------------------------
1 | group 'com.hansonwang99'
2 | version '1.0-SNAPSHOT'
3 |
4 | buildscript {
5 | ext.kotlin_version = '1.1.1'
6 | ext.springboot_version = '1.5.2.RELEASE'
7 |
8 | repositories {
9 | mavenCentral()
10 | }
11 | dependencies {
12 | // Kotlin Gradle插件
13 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
14 | // SpringBoot Gradle插件
15 | classpath("org.springframework.boot:spring-boot-gradle-plugin:$springboot_version")
16 | // Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件
17 | classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version")
18 | classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")
19 | }
20 | }
21 |
22 | apply plugin: 'java'
23 | apply plugin: 'kotlin'
24 | apply plugin: 'kotlin-spring'
25 | apply plugin: 'kotlin-jpa'
26 | apply plugin: 'org.springframework.boot'
27 |
28 | sourceCompatibility = 1.8
29 | targetCompatibility = 1.8
30 |
31 | repositories {
32 | mavenCentral()
33 | }
34 |
35 | dependencies {
36 | compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
37 | testCompile group: 'junit', name: 'junit', version: '4.12'
38 | compile("org.springframework.boot:spring-boot-starter-web")
39 | testCompile("org.springframework.boot:spring-boot-starter-test")
40 | compile("org.springframework.boot:spring-boot-starter-data-jpa")
41 | compile('mysql:mysql-connector-java:5.1.13')
42 | }
43 |
--------------------------------------------------------------------------------
/kotlin_with_springbt/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'kotlin_with_springbt'
2 |
3 |
--------------------------------------------------------------------------------
/kotlin_with_springbt/src/main/kotlin/com/hansonwang99/kotlin/Application.kt:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.kotlin
2 |
3 | import org.springframework.boot.SpringApplication
4 | import org.springframework.boot.autoconfigure.SpringBootApplication
5 |
6 | /**
7 | * Created by Administrator on 2018/1/23.
8 | */
9 |
10 | @SpringBootApplication
11 | class Application
12 |
13 | fun main(args: Array) {
14 | SpringApplication.run(Application::class.java, *args)
15 | }
--------------------------------------------------------------------------------
/kotlin_with_springbt/src/main/kotlin/com/hansonwang99/kotlin/controller/PeopleController.kt:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.kotlin.controller
2 |
3 | import com.hansonwang99.kotlin.service.PeopleService
4 | import org.springframework.beans.factory.annotation.Autowired
5 | import org.springframework.stereotype.Controller
6 | import org.springframework.web.bind.annotation.GetMapping
7 | import org.springframework.web.bind.annotation.RequestParam
8 | import org.springframework.web.bind.annotation.ResponseBody
9 |
10 | /**
11 | * Created by Administrator on 2018/1/23.
12 | */
13 | @Controller
14 | class PeopleController {
15 | @Autowired
16 | val peopleService: PeopleService? = null
17 |
18 | @GetMapping(value = "/hello")
19 | @ResponseBody
20 | fun hello(@RequestParam(value = "lastName") lastName: String): Any {
21 | val peoples = peopleService?.findByLastName(lastName)
22 | val map = HashMap()
23 | map.put("hello", peoples!!)
24 | return map
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/kotlin_with_springbt/src/main/kotlin/com/hansonwang99/kotlin/entity/People.kt:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.kotlin.entity
2 |
3 | import java.util.*
4 | import javax.persistence.Entity
5 | import javax.persistence.GeneratedValue
6 | import javax.persistence.GenerationType
7 | import javax.persistence.Id
8 |
9 | /**
10 | * Created by Administrator on 2018/1/23.
11 | */
12 |
13 | @Entity
14 | class People(
15 | @Id @GeneratedValue(strategy = GenerationType.AUTO)
16 | val id: Long?,
17 | val firstName: String?,
18 | val lastName: String?,
19 | val gender: String?,
20 | val age: Int?,
21 | val gmtCreated: Date,
22 | val gmtModified: Date
23 | ) {
24 | override fun toString(): String {
25 | return "People(id=$id, firstName='$firstName', lastName='$lastName', gender='$gender', age=$age, gmtCreated=$gmtCreated, gmtModified=$gmtModified)"
26 | }
27 | }
--------------------------------------------------------------------------------
/kotlin_with_springbt/src/main/kotlin/com/hansonwang99/kotlin/repository/PeopleRepository.kt:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.kotlin.repository
2 |
3 | import com.hansonwang99.kotlin.entity.People
4 | import org.springframework.data.repository.CrudRepository
5 |
6 | /**
7 | * Created by Administrator on 2018/1/23.
8 | */
9 |
10 | interface PeopleRepository : CrudRepository {
11 | fun findByLastName(lastName: String): List?
12 | }
--------------------------------------------------------------------------------
/kotlin_with_springbt/src/main/kotlin/com/hansonwang99/kotlin/service/PeopleService.kt:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.kotlin.service
2 |
3 | import com.hansonwang99.kotlin.entity.People
4 | import com.hansonwang99.kotlin.repository.PeopleRepository
5 | import org.springframework.beans.factory.annotation.Autowired
6 | import org.springframework.stereotype.Service
7 |
8 | /**
9 | * Created by Administrator on 2018/1/23.
10 | */
11 | @Service
12 | class PeopleService : PeopleRepository {
13 |
14 | @Autowired
15 | val peopleRepository: PeopleRepository? = null
16 |
17 |
18 | override fun findByLastName(lastName: String): List? {
19 | return peopleRepository?.findByLastName(lastName)
20 | }
21 |
22 | override fun save(entity: S): S? {
23 | return peopleRepository?.save(entity)
24 | }
25 |
26 | override fun save(entities: MutableIterable?): MutableIterable? {
27 | return peopleRepository?.save(entities)
28 | }
29 |
30 | override fun delete(entities: MutableIterable?) {
31 | }
32 |
33 | override fun delete(entity: People?) {
34 | }
35 |
36 | override fun delete(id: Long?) {
37 | }
38 |
39 | override fun findAll(ids: MutableIterable?): MutableIterable? {
40 | return peopleRepository?.findAll(ids)
41 | }
42 |
43 | override fun findAll(): MutableIterable? {
44 | return peopleRepository?.findAll()
45 | }
46 |
47 | override fun exists(id: Long?): Boolean {
48 | return peopleRepository?.exists(id)!!
49 | }
50 |
51 | override fun count(): Long {
52 | return peopleRepository?.count()!!
53 | }
54 |
55 | override fun findOne(id: Long?): People? {
56 | return peopleRepository?.findOne(id)
57 | }
58 |
59 | override fun deleteAll() {
60 | }
61 |
62 |
63 | }
--------------------------------------------------------------------------------
/kotlin_with_springbt/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.datasource.url = jdbc:mysql://localhost:3306/easykotlin
2 | spring.datasource.username = root
3 | spring.datasource.password = 111111
4 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
5 | # Specify the DBMS
6 | spring.jpa.database = MYSQL
7 | # Keep the connection alive if idle for a long time (needed in production)
8 | spring.datasource.testWhileIdle = true
9 | spring.datasource.validationQuery = SELECT 1
10 | # Show or not log for each sql query
11 | spring.jpa.show-sql = true
12 | # Hibernate ddl auto (create, create-drop, update)
13 | spring.jpa.hibernate.ddl-auto = update
14 | # Naming strategy
15 | spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
16 | # The SQL dialect makes Hibernate generate better SQL for the chosen database
17 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
18 |
19 | server.port=7000
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/.DS_Store
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/sba_client_2_0/.DS_Store
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 | .sts4-cache
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_boot_admin2.0_demo/sba_client_2_0/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/sba_client_2_0/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
2 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | sba_client_2_0
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | sba_client_2_0
12 | Demo project for Spring Boot Admin 2.0
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.3.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | de.codecentric
30 | spring-boot-admin-starter-client
31 | 2.0.1
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-starter-actuator
37 |
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-starter-web
42 |
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-test
47 | test
48 |
49 |
50 |
51 |
52 |
53 |
54 | org.springframework.boot
55 | spring-boot-maven-plugin
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/sba_client_2_0/src/.DS_Store
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/src/main/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/sba_client_2_0/src/main/.DS_Store
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/src/main/java/cn/codesheep/sba_client_2_0/SbaClient20Application.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.sba_client_2_0;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SbaClient20Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SbaClient20Application.class, args);
11 | }
12 |
13 | // @Configuration
14 | // public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
15 | // @Override
16 | // protected void configure(HttpSecurity http) throws Exception {
17 | // http.authorizeRequests().anyRequest().permitAll()
18 | // .and().csrf().disable();
19 | // }
20 | // }
21 | }
22 |
23 |
24 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=8081
2 | spring.application.name=Spring Boot Client
3 | spring.boot.admin.client.url=http://localhost:8080
4 | management.endpoints.web.exposure.include=*
5 |
6 | spring.boot.admin.client.username=admin
7 | spring.boot.admin.client.password=111111
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_client_2_0/src/test/java/cn/codesheep/sba_client_2_0/SbaClient20ApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.sba_client_2_0;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SbaClient20ApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/sba_server_2_0/.DS_Store
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 | .sts4-cache
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_boot_admin2.0_demo/sba_server_2_0/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/spring_boot_admin2.0_demo/sba_server_2_0/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
2 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | sba_server_2_0
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | sba_server_2_0
12 | Demo project for Spring Boot Admin 2.0
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.3.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | de.codecentric
30 | spring-boot-admin-starter-server
31 | 2.0.1
32 |
33 |
34 |
35 | de.codecentric
36 | spring-boot-admin-server-ui
37 | 2.0.1
38 |
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-starter-security
43 |
44 |
45 |
46 | org.springframework.boot
47 | spring-boot-starter-web
48 |
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-starter-test
53 | test
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.springframework.boot
61 | spring-boot-maven-plugin
62 |
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/src/main/java/cn/codesheep/sba_server_2_0/SbaServer20Application.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.sba_server_2_0;
2 |
3 | import de.codecentric.boot.admin.server.config.AdminServerAutoConfiguration;
4 | import de.codecentric.boot.admin.server.config.AdminServerProperties;
5 | import de.codecentric.boot.admin.server.config.EnableAdminServer;
6 | import org.springframework.boot.SpringApplication;
7 | import org.springframework.boot.autoconfigure.SpringBootApplication;
8 | import org.springframework.context.annotation.Configuration;
9 | import org.springframework.context.annotation.Profile;
10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
12 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
13 | import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
14 |
15 | @SpringBootApplication
16 | @EnableAdminServer
17 | public class SbaServer20Application {
18 |
19 | public static void main(String[] args) {
20 | SpringApplication.run(SbaServer20Application.class, args);
21 | }
22 |
23 | @Profile("insecure")
24 | @Configuration
25 | public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter{
26 |
27 | @Override
28 | protected void configure(HttpSecurity http) throws Exception {
29 | http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();
30 | }
31 | }
32 |
33 | @Profile("secure")
34 | @Configuration
35 | public static class SecuritySecureConfig extends WebSecurityConfigurerAdapter{
36 |
37 | private String adminContextPath;
38 |
39 | public SecuritySecureConfig( AdminServerProperties adminServerProperties ) {
40 | this.adminContextPath = adminServerProperties.getContextPath();
41 | }
42 |
43 | @Override
44 | protected void configure(HttpSecurity http) throws Exception {
45 | SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
46 | successHandler.setTargetUrlParameter("redirectTo");
47 |
48 | http.authorizeRequests().antMatchers(adminContextPath+"/assets/**").permitAll()
49 | .antMatchers(adminContextPath+"/login").permitAll().anyRequest().authenticated().and().formLogin()
50 | .loginPage(adminContextPath+"/login").successHandler(successHandler).and().logout()
51 | .logoutUrl(adminContextPath+"/logout").and().httpBasic().and().csrf().disable();
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/src/main/resources/application-secure.properties:
--------------------------------------------------------------------------------
1 | spring.security.user.name=admin
2 | spring.security.user.password=111111
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.profiles.active=secure
--------------------------------------------------------------------------------
/spring_boot_admin2.0_demo/sba_server_2_0/src/test/java/cn/codesheep/sba_server_2_0/SbaServer20ApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.sba_server_2_0;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SbaServer20ApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springboot_es_demo/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springboot_es_demo/.DS_Store
--------------------------------------------------------------------------------
/springboot_es_demo/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.hansonwang99
7 | springboot_es_demo
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | springboot_es_demo
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.9.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-data-elasticsearch
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-web
35 |
36 |
37 |
38 | org.springframework.boot
39 | spring-boot-starter-test
40 | test
41 |
42 |
43 |
44 | io.searchbox
45 | jest
46 |
47 |
48 |
49 | net.java.dev.jna
50 | jna
51 |
52 |
53 |
54 |
55 |
56 |
57 | org.springframework.boot
58 | spring-boot-maven-plugin
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/springboot_es_demo/src/main/java/com/hansonwang99/springboot_es_demo/SpringbootEsDemoApplication.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.springboot_es_demo;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringbootEsDemoApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringbootEsDemoApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/springboot_es_demo/src/main/java/com/hansonwang99/springboot_es_demo/controller/EntityController.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.springboot_es_demo.controller;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.hansonwang99.springboot_es_demo.entity.Entity;
7 | import com.hansonwang99.springboot_es_demo.service.TestService;
8 | import org.apache.commons.lang.StringUtils;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.web.bind.annotation.RequestMapping;
11 | import org.springframework.web.bind.annotation.RequestMethod;
12 | import org.springframework.web.bind.annotation.RestController;
13 |
14 | @RestController
15 | @RequestMapping("/entityController")
16 | public class EntityController {
17 |
18 |
19 | @Autowired
20 | TestService cityESService;
21 |
22 | @RequestMapping(value="/save", method=RequestMethod.GET)
23 | public String save(long id, String name) {
24 | System.out.println("save 接口");
25 | if(id>0 && StringUtils.isNotEmpty(name)) {
26 | Entity newEntity = new Entity(id,name);
27 | List addList = new ArrayList();
28 | addList.add(newEntity);
29 | cityESService.saveEntity(addList);
30 | return "OK";
31 | }else {
32 | return "Bad input value";
33 | }
34 | }
35 |
36 | @RequestMapping(value="/search", method=RequestMethod.GET)
37 | public List save(String name) {
38 | List entityList = null;
39 | if(StringUtils.isNotEmpty(name)) {
40 | entityList = cityESService.searchEntity(name);
41 | }
42 | return entityList;
43 | }
44 | }
--------------------------------------------------------------------------------
/springboot_es_demo/src/main/java/com/hansonwang99/springboot_es_demo/entity/Entity.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.springboot_es_demo.entity;
2 |
3 | import java.io.Serializable;
4 |
5 | import org.springframework.data.elasticsearch.annotations.Document;
6 |
7 | public class Entity implements Serializable{
8 |
9 | private static final long serialVersionUID = -763638353551774166L;
10 |
11 | public static final String INDEX_NAME = "index_entity";
12 |
13 | public static final String TYPE = "tstype";
14 |
15 | private Long id;
16 |
17 | private String name;
18 |
19 | public Entity() {
20 | super();
21 | }
22 |
23 | public Entity(Long id, String name) {
24 | this.id = id;
25 | this.name = name;
26 | }
27 |
28 | public Long getId() {
29 | return id;
30 | }
31 |
32 | public void setId(Long id) {
33 | this.id = id;
34 | }
35 |
36 | public String getName() {
37 | return name;
38 | }
39 |
40 | public void setName(String name) {
41 | this.name = name;
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/springboot_es_demo/src/main/java/com/hansonwang99/springboot_es_demo/service/TestService.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.springboot_es_demo.service;
2 |
3 | import com.hansonwang99.springboot_es_demo.entity.Entity;
4 |
5 | import java.util.List;
6 |
7 | public interface TestService {
8 |
9 | void saveEntity(Entity entity);
10 |
11 | void saveEntity(List entityList);
12 |
13 | List searchEntity(String searchContent);
14 | }
15 |
--------------------------------------------------------------------------------
/springboot_es_demo/src/main/java/com/hansonwang99/springboot_es_demo/service/impl/TestServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.springboot_es_demo.service.impl;
2 |
3 | import java.io.IOException;
4 | import java.util.List;
5 |
6 | import com.hansonwang99.springboot_es_demo.entity.Entity;
7 | import com.hansonwang99.springboot_es_demo.service.TestService;
8 | import org.elasticsearch.index.query.QueryBuilders;
9 | import org.elasticsearch.search.builder.SearchSourceBuilder;
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 | import org.springframework.beans.factory.annotation.Autowired;
13 | import org.springframework.stereotype.Service;
14 | import io.searchbox.client.JestClient;
15 | import io.searchbox.client.JestResult;
16 | import io.searchbox.core.Bulk;
17 | import io.searchbox.core.Index;
18 | import io.searchbox.core.Search;
19 |
20 | @Service
21 | public class TestServiceImpl implements TestService {
22 |
23 | private static final Logger LOGGER = LoggerFactory.getLogger(TestServiceImpl.class);
24 |
25 | @Autowired
26 | private JestClient jestClient;
27 |
28 | @Override
29 | public void saveEntity(Entity entity) {
30 | Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
31 | try {
32 | jestClient.execute(index);
33 | LOGGER.info("ES 插入完成");
34 | } catch (IOException e) {
35 | e.printStackTrace();
36 | LOGGER.error(e.getMessage());
37 | }
38 | }
39 |
40 |
41 | /**
42 | * 批量保存内容到ES
43 | */
44 | @Override
45 | public void saveEntity(List entityList) {
46 | Bulk.Builder bulk = new Bulk.Builder();
47 | for(Entity entity : entityList) {
48 | Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
49 | bulk.addAction(index);
50 | }
51 | try {
52 | jestClient.execute(bulk.build());
53 | LOGGER.info("ES 插入完成");
54 | } catch (IOException e) {
55 | e.printStackTrace();
56 | LOGGER.error(e.getMessage());
57 | }
58 | }
59 |
60 | /**
61 | * 在ES中搜索内容
62 | */
63 | @Override
64 | public List searchEntity(String searchContent){
65 | SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
66 | //searchSourceBuilder.query(QueryBuilders.queryStringQuery(searchContent));
67 | //searchSourceBuilder.field("name");
68 | searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));
69 | Search search = new Search.Builder(searchSourceBuilder.toString())
70 | .addIndex(Entity.INDEX_NAME).addType(Entity.TYPE).build();
71 | try {
72 | JestResult result = jestClient.execute(search);
73 | return result.getSourceAsObjectList(Entity.class);
74 | } catch (IOException e) {
75 | LOGGER.error(e.getMessage());
76 | e.printStackTrace();
77 | }
78 | return null;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/springboot_es_demo/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 6325
3 |
4 | spring:
5 | elasticsearch:
6 | jest:
7 | uris:
8 | - http://xxx.xxx.xxx.xxx:9200 # ES服务器的地址
9 | read-timeout: 5000
--------------------------------------------------------------------------------
/springboot_es_demo/src/test/java/com/hansonwang99/springboot_es_demo/SpringbootEsDemoApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99.springboot_es_demo;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbootEsDemoApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_admin_server/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.hansonwang99
7 | springbt_admin_server
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | springbt_admin_server
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.9.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter
31 |
32 |
33 |
34 |
35 | de.codecentric
36 | spring-boot-admin-server
37 | 1.5.7
38 |
39 |
40 |
41 | de.codecentric
42 | spring-boot-admin-server-ui
43 | 1.5.7
44 |
45 |
46 |
47 | org.projectlombok
48 | lombok
49 | true
50 |
51 |
52 | org.springframework.boot
53 | spring-boot-starter-test
54 | test
55 |
56 |
57 |
58 |
59 |
60 |
61 | org.springframework.boot
62 | spring-boot-maven-plugin
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/springbt_admin_server/src/main/java/com/hansonwang99/SpringbtAdminServerApplication.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99;
2 |
3 | import de.codecentric.boot.admin.config.EnableAdminServer;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 |
7 | @EnableAdminServer
8 | @SpringBootApplication
9 | public class SpringbtAdminServerApplication {
10 |
11 | public static void main(String[] args) {
12 | SpringApplication.run(SpringbtAdminServerApplication.class, args);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/springbt_admin_server/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=8081
--------------------------------------------------------------------------------
/springbt_admin_server/src/test/java/com/hansonwang99/SpringbtAdminServerApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.hansonwang99;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtAdminServerApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_ehcache/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 | .sts4-cache
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/
--------------------------------------------------------------------------------
/springbt_ehcache/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springbt_ehcache/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/springbt_ehcache/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip
2 |
--------------------------------------------------------------------------------
/springbt_ehcache/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | springbt_ehcache
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | springbt_ehcache
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.9.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 |
41 | org.mybatis.spring.boot
42 | mybatis-spring-boot-starter
43 | 1.3.2
44 |
45 |
46 |
47 |
48 | mysql
49 | mysql-connector-java
50 | runtime
51 |
52 |
53 |
54 |
55 | org.springframework.boot
56 | spring-boot-starter-cache
57 |
58 |
59 |
60 |
61 | net.sf.ehcache
62 | ehcache
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | org.springframework.boot
71 | spring-boot-maven-plugin
72 |
73 |
74 |
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/java/cn/codesheep/springbt_ehcache/SpringbtEhcacheApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_ehcache;
2 |
3 | import org.mybatis.spring.annotation.MapperScan;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.cache.annotation.EnableCaching;
7 |
8 | @SpringBootApplication
9 | @MapperScan("cn.codesheep.springbt_ehcache")
10 | @EnableCaching
11 | public class SpringbtEhcacheApplication {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(SpringbtEhcacheApplication.class, args);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/java/cn/codesheep/springbt_ehcache/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_ehcache.controller;
2 |
3 | import cn.codesheep.springbt_ehcache.entity.User;
4 | import cn.codesheep.springbt_ehcache.service.UserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 |
7 | import org.springframework.cache.CacheManager;
8 | import org.springframework.web.bind.annotation.*;
9 |
10 | import java.util.List;
11 |
12 | @RestController
13 | public class UserController {
14 |
15 | @Autowired
16 | private UserService userService;
17 |
18 | @Autowired
19 | CacheManager cacheManager;
20 |
21 | @GetMapping("/users")
22 | public List getUsers() {
23 | return userService.getUsers();
24 | }
25 |
26 | @GetMapping("/adduser")
27 | public int addSser() {
28 | User user = new User();
29 | user.setUserId(4l);
30 | user.setUserName("赵四");
31 | user.setUserAge(38);
32 | return userService.addUser(user);
33 | }
34 |
35 | @RequestMapping( value = "/getusersbyname", method = RequestMethod.POST)
36 | public List geUsersByName( @RequestBody User user ) {
37 | System.out.println( "-------------------------------------------" );
38 | System.out.println("call /getusersbyname");
39 | System.out.println(cacheManager.toString());
40 | List users = userService.getUsersByName( user.getUserName() );
41 | return users;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/java/cn/codesheep/springbt_ehcache/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_ehcache.entity;
2 |
3 | public class User {
4 |
5 | private Long userId;
6 | private String userName;
7 | private Integer userAge;
8 |
9 | public Long getUserId() {
10 | return userId;
11 | }
12 |
13 | public void setUserId(Long userId) {
14 | this.userId = userId;
15 | }
16 |
17 | public String getUserName() {
18 | return userName;
19 | }
20 |
21 | public void setUserName(String userName) {
22 | this.userName = userName;
23 | }
24 |
25 | public Integer getUserAge() {
26 | return userAge;
27 | }
28 |
29 | public void setUserAge(Integer userAge) {
30 | this.userAge = userAge;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/java/cn/codesheep/springbt_ehcache/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_ehcache.mapper;
2 |
3 | import cn.codesheep.springbt_ehcache.entity.User;
4 |
5 | import java.util.List;
6 |
7 | public interface UserMapper {
8 |
9 | List getUsers();
10 |
11 | int addUser(User user);
12 |
13 | List getUsersByName( String userName );
14 | }
15 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/java/cn/codesheep/springbt_ehcache/service/UserService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_ehcache.service;
2 |
3 | import cn.codesheep.springbt_ehcache.entity.User;
4 | import cn.codesheep.springbt_ehcache.mapper.UserMapper;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.cache.annotation.Cacheable;
7 | import org.springframework.stereotype.Service;
8 |
9 | import java.util.List;
10 |
11 |
12 | @Service
13 | public class UserService {
14 |
15 | @Autowired
16 | private UserMapper userMapper;
17 |
18 | public List getUsers() {
19 | return userMapper.getUsers();
20 | }
21 |
22 | public int addUser( User user ) {
23 | return userMapper.addUser(user);
24 | }
25 |
26 | @Cacheable(value = "user", key = "#userName")
27 | public List getUsersByName( String userName ) {
28 | List users = userMapper.getUsersByName( userName );
29 | System.out.println( "从数据库读取,而非读取缓存!" );
30 | return users;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | server.port=80
3 |
4 | # Mysql 数据源配置
5 | spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
6 | spring.datasource.username=root
7 | spring.datasource.password=xxxxxx
8 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
9 |
10 | # mybatis配置
11 | mybatis.type-aliases-package=cn.codesheep.springbt_ehcache.entity
12 | mybatis.mapper-locations=classpath:mapper/*.xml
13 | mybatis.configuration.map-underscore-to-camel-case=true
14 |
15 | spring.cache.ehcache.config=classpath:ehcache.xml
16 |
17 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/resources/ehcache.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
17 |
18 |
22 |
23 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/main/resources/mapper/UserMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | SELECT * FROM tbl_user
8 |
9 |
10 |
11 | insert into tbl_user(user_id, user_name, user_age) values(#{userId}, #{userName}, #{userAge})
12 |
13 |
14 |
15 | select * from tbl_user where user_name=#{userName}
16 |
17 |
18 |
--------------------------------------------------------------------------------
/springbt_ehcache/src/test/java/cn/codesheep/springbt_ehcache/SpringbtEhcacheApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_ehcache;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtEhcacheApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_evcache/evcache-client-4.137.0-SNAPSHOT.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springbt_evcache/evcache-client-4.137.0-SNAPSHOT.jar
--------------------------------------------------------------------------------
/springbt_evcache/src/main/java/cn/codesheep/springbt_evcache/SpringbtEvcacheApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_evcache;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringbtEvcacheApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringbtEvcacheApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_evcache/src/main/java/cn/codesheep/springbt_evcache/config/EVCacheConfig.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_evcache.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 |
6 | @Configuration
7 | public class EVCacheConfig {
8 |
9 | @Bean
10 | public EVCacheClientSample evcacheClient() {
11 | EVCacheClientSample evCacheClient = new EVCacheClientSample();
12 | return evCacheClient;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/springbt_evcache/src/main/java/cn/codesheep/springbt_evcache/controller/EVCacheTestController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_evcache.controller;
2 |
3 | import cn.codesheep.springbt_evcache.service.EVCacheService;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.web.bind.annotation.GetMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | @RestController
9 | public class EVCacheTestController {
10 |
11 | @Autowired
12 | private EVCacheService evCacheService;
13 |
14 | @GetMapping("/testevcache")
15 | public void testEvcache() {
16 |
17 | try {
18 |
19 | // Set ten keys to different values
20 | for ( int i = 0; i < 10; i++ ) {
21 | String key = "key_" + i;
22 | String value = "data_" + i;
23 | // Set the TTL to 10s
24 | int ttl = 10;
25 | evCacheService.setKey(key, value, ttl);
26 | }
27 |
28 | // Do a "get" for each of those same keys
29 | for (int i = 0; i < 10; i++) {
30 | String key = "key_" + i;
31 | String value = evCacheService.getKey(key);
32 | System.out.println("Get of " + key + " returned " + value);
33 | }
34 | } catch (Exception e) {
35 | e.printStackTrace();
36 | }
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/springbt_evcache/src/main/java/cn/codesheep/springbt_evcache/service/EVCacheService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_evcache.service;
2 |
3 | import cn.codesheep.springbt_evcache.config.EVCacheClientSample;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.stereotype.Service;
6 |
7 | @Service
8 | public class EVCacheService {
9 |
10 | @Autowired
11 | private EVCacheClientSample evCacheClient;
12 |
13 | public void setKey( String key, String value, int timeToLive ) {
14 | try {
15 | evCacheClient.setKey( key, value, timeToLive );
16 | } catch (Exception e) {
17 | e.printStackTrace();
18 | }
19 | }
20 |
21 | public String getKey( String key ) {
22 | return evCacheClient.getKey( key );
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/springbt_evcache/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=8899
--------------------------------------------------------------------------------
/springbt_evcache/src/test/java/cn/codesheep/springbt_evcache/SpringbtEvcacheApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_evcache;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtEvcacheApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_guava_cache/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 1.5.9.RELEASE
9 |
10 |
11 | cn.codesheep
12 | springbt_guava_cache
13 | 0.0.1-SNAPSHOT
14 | springbt_guava_cache
15 | springbt_guava_cache
16 |
17 |
18 | 1.8
19 |
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-web
25 |
26 |
27 |
28 | org.springframework.boot
29 | spring-boot-starter-test
30 | test
31 |
32 |
33 |
34 |
35 | org.mybatis.spring.boot
36 | mybatis-spring-boot-starter
37 | 1.3.2
38 |
39 |
40 |
41 |
42 | mysql
43 | mysql-connector-java
44 | runtime
45 |
46 |
47 |
48 | org.springframework.boot
49 | spring-boot-starter-cache
50 |
51 |
52 |
53 |
54 | com.google.guava
55 | guava
56 | 27.0.1-jre
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | org.springframework.boot
65 | spring-boot-maven-plugin
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/java/cn/codesheep/springbt_guava_cache/SpringbtGuavaCacheApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache;
2 |
3 | import org.mybatis.spring.annotation.MapperScan;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.cache.annotation.EnableCaching;
7 |
8 | @SpringBootApplication
9 | @MapperScan("cn.codesheep.springbt_guava_cache")
10 | @EnableCaching
11 | public class SpringbtGuavaCacheApplication {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(SpringbtGuavaCacheApplication.class, args);
15 | }
16 |
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/java/cn/codesheep/springbt_guava_cache/config/GuavaCacheConfig.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache.config;
2 |
3 | import com.google.common.cache.CacheBuilder;
4 | import org.springframework.cache.CacheManager;
5 | import org.springframework.cache.annotation.EnableCaching;
6 | import org.springframework.cache.guava.GuavaCacheManager;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.Configuration;
9 |
10 | import java.util.concurrent.TimeUnit;
11 |
12 | @Configuration
13 | @EnableCaching
14 | public class GuavaCacheConfig {
15 |
16 | @Bean
17 | public CacheManager cacheManager() {
18 | GuavaCacheManager cacheManager = new GuavaCacheManager();
19 | cacheManager.setCacheBuilder(
20 | CacheBuilder.newBuilder().
21 | expireAfterWrite(10, TimeUnit.SECONDS).
22 | maximumSize(1000));
23 | return cacheManager;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/java/cn/codesheep/springbt_guava_cache/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache.controller;
2 |
3 | import cn.codesheep.springbt_guava_cache.entity.User;
4 | import cn.codesheep.springbt_guava_cache.service.UserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 |
7 | import org.springframework.cache.CacheManager;
8 | import org.springframework.web.bind.annotation.*;
9 |
10 | import java.util.List;
11 |
12 | @RestController
13 | public class UserController {
14 |
15 | @Autowired
16 | private UserService userService;
17 |
18 | @Autowired
19 | CacheManager cacheManager;
20 |
21 | @GetMapping("/users")
22 | public List getUsers() {
23 | return userService.getUsers();
24 | }
25 |
26 | @GetMapping("/adduser")
27 | public int addSser() {
28 | User user = new User();
29 | user.setUserId(4l);
30 | user.setUserName("赵四");
31 | user.setUserAge(38);
32 | return userService.addUser(user);
33 | }
34 |
35 | @RequestMapping( value = "/getusersbyname", method = RequestMethod.POST)
36 | public List geUsersByName( @RequestBody User user ) {
37 | System.out.println( "-------------------------------------------" );
38 | System.out.println("call /getusersbyname");
39 | System.out.println(cacheManager.toString());
40 | List users = userService.getUsersByName( user.getUserName() );
41 | return users;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/java/cn/codesheep/springbt_guava_cache/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache.entity;
2 |
3 | public class User {
4 |
5 | private Long userId;
6 | private String userName;
7 | private Integer userAge;
8 |
9 | public Long getUserId() {
10 | return userId;
11 | }
12 |
13 | public void setUserId(Long userId) {
14 | this.userId = userId;
15 | }
16 |
17 | public String getUserName() {
18 | return userName;
19 | }
20 |
21 | public void setUserName(String userName) {
22 | this.userName = userName;
23 | }
24 |
25 | public Integer getUserAge() {
26 | return userAge;
27 | }
28 |
29 | public void setUserAge(Integer userAge) {
30 | this.userAge = userAge;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/java/cn/codesheep/springbt_guava_cache/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache.mapper;
2 |
3 | import cn.codesheep.springbt_guava_cache.entity.User;
4 |
5 | import java.util.List;
6 |
7 | public interface UserMapper {
8 |
9 | List getUsers();
10 |
11 | int addUser(User user);
12 |
13 | List getUsersByName(String userName);
14 | }
15 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/java/cn/codesheep/springbt_guava_cache/service/UserService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache.service;
2 |
3 | import cn.codesheep.springbt_guava_cache.entity.User;
4 | import cn.codesheep.springbt_guava_cache.mapper.UserMapper;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.cache.annotation.Cacheable;
7 | import org.springframework.stereotype.Service;
8 |
9 | import java.util.List;
10 |
11 |
12 | @Service
13 | public class UserService {
14 |
15 | @Autowired
16 | private UserMapper userMapper;
17 |
18 | public List getUsers() {
19 | return userMapper.getUsers();
20 | }
21 |
22 | public int addUser( User user ) {
23 | return userMapper.addUser(user);
24 | }
25 |
26 | @Cacheable(value = "user", key = "#userName")
27 | public List getUsersByName( String userName ) {
28 | List users = userMapper.getUsersByName( userName );
29 | System.out.println( "从数据库读取,而非读取缓存!" );
30 | return users;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=82
2 |
3 | # Mysql ����Դ����
4 | spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
5 | spring.datasource.username=root
6 | spring.datasource.password=xxxxxx
7 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
8 |
9 | # mybatis����
10 | mybatis.type-aliases-package=cn.codesheep.springbt_guava_cache.entity
11 | mybatis.mapper-locations=classpath:mapper/*.xml
12 | mybatis.configuration.map-underscore-to-camel-case=true
--------------------------------------------------------------------------------
/springbt_guava_cache/src/main/resources/mapper/UserMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | SELECT * FROM tbl_user
8 |
9 |
10 |
11 | insert into tbl_user(user_id, user_name, user_age) values(#{userId}, #{userName}, #{userAge})
12 |
13 |
14 |
15 | select * from tbl_user where user_name=#{userName}
16 |
17 |
18 |
--------------------------------------------------------------------------------
/springbt_guava_cache/src/test/java/cn/codesheep/springbt_guava_cache/SpringbtGuavaCacheApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_guava_cache;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtGuavaCacheApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | springbt_mybatis_sqlserver
8 | 0.0.1
9 | jar
10 |
11 | springbt_mybatis_sqlserver
12 | springbt_mybatis_sqlserver
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.16.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 |
41 | org.mybatis.spring.boot
42 | mybatis-spring-boot-starter
43 | 1.3.2
44 |
45 |
46 |
47 |
48 | com.microsoft.sqlserver
49 | sqljdbc4
50 | 4.0
51 |
52 |
53 |
54 |
55 | com.alibaba
56 | druid-spring-boot-starter
57 | 1.1.0
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | org.springframework.boot
66 | spring-boot-maven-plugin
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/java/cn/codesheep/springbt_mybatis_sqlserver/SpringbtMybatisSqlserverApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver;
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("cn.codesheep.springbt_mybatis_sqlserver")
9 | public class SpringbtMybatisSqlserverApplication {
10 |
11 | public static void main(String[] args) {
12 | SpringApplication.run(SpringbtMybatisSqlserverApplication.class, args);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/java/cn/codesheep/springbt_mybatis_sqlserver/controller/UserController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver.controller;
2 |
3 | import cn.codesheep.springbt_mybatis_sqlserver.entity.User;
4 | import cn.codesheep.springbt_mybatis_sqlserver.service.IUserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.beans.factory.annotation.Qualifier;
7 | import org.springframework.web.bind.annotation.RequestBody;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestMethod;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import java.util.List;
13 |
14 | @RestController
15 | public class UserController {
16 |
17 | @Autowired
18 | private IUserService userService;
19 |
20 | @RequestMapping(value = "/getAllUser", method = RequestMethod.GET)
21 | public List getAllUser() {
22 | return userService.getAllUsers();
23 | }
24 |
25 | @RequestMapping(value = "/addUser", method = RequestMethod.POST)
26 | public int addUser( @RequestBody User user ) {
27 | return userService.addUser( user );
28 | }
29 |
30 | @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
31 | public int deleteUser( @RequestBody User user ) {
32 | return userService.deleteUser( user );
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/java/cn/codesheep/springbt_mybatis_sqlserver/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver.entity;
2 |
3 | import java.util.Date;
4 |
5 | public class User {
6 |
7 | private Long userId;
8 | private String userName;
9 | private Boolean sex;
10 | private String createdTime;
11 |
12 | public Long getUserId() {
13 | return userId;
14 | }
15 |
16 | public void setUserId(Long userId) {
17 | this.userId = userId;
18 | }
19 |
20 | public String getUserName() {
21 | return userName;
22 | }
23 |
24 | public void setUserName(String userName) {
25 | this.userName = userName;
26 | }
27 |
28 | public Boolean getSex() {
29 | return sex;
30 | }
31 |
32 | public void setSex(Boolean sex) {
33 | this.sex = sex;
34 | }
35 |
36 | public String getCreatedTime() {
37 | return createdTime;
38 | }
39 |
40 | public void setCreatedTime(String createdTime) {
41 | this.createdTime = createdTime;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/java/cn/codesheep/springbt_mybatis_sqlserver/mapper/UserMapper.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver.mapper;
2 |
3 | import cn.codesheep.springbt_mybatis_sqlserver.entity.User;
4 |
5 | import java.util.List;
6 |
7 | public interface UserMapper {
8 |
9 | List getAllUsers();
10 | int addUser( User user );
11 | int deleteUser( User user );
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/java/cn/codesheep/springbt_mybatis_sqlserver/service/IUserService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver.service;
2 |
3 | import cn.codesheep.springbt_mybatis_sqlserver.entity.User;
4 |
5 | import java.util.List;
6 |
7 | public interface IUserService {
8 |
9 | List getAllUsers();
10 | int addUser( User user );
11 | int deleteUser( User user );
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/java/cn/codesheep/springbt_mybatis_sqlserver/service/impl/UserServiceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver.service.impl;
2 |
3 | import cn.codesheep.springbt_mybatis_sqlserver.entity.User;
4 | import cn.codesheep.springbt_mybatis_sqlserver.mapper.UserMapper;
5 | import cn.codesheep.springbt_mybatis_sqlserver.service.IUserService;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.context.annotation.Primary;
8 | import org.springframework.stereotype.Service;
9 |
10 | import java.text.SimpleDateFormat;
11 | import java.util.Date;
12 | import java.util.List;
13 |
14 | @Service
15 | @Primary // 注意这个注解的添加,否则会报:Autowired required a single bean, but 2 were found!!! (疑问?难道UserServiceImpl和IUserService不是一个东西嘛?)
16 | public class UserServiceImpl implements IUserService {
17 |
18 | @Autowired
19 | private UserMapper userMapper;
20 |
21 | @Override
22 | public List getAllUsers() {
23 | return userMapper.getAllUsers();
24 | }
25 |
26 | @Override
27 | public int addUser(User user) {
28 | SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
29 | user.setCreatedTime( form.format(new Date()) );
30 | return userMapper.addUser( user );
31 | }
32 |
33 | @Override
34 | public int deleteUser(User user) {
35 | return userMapper.deleteUser( user );
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/resources/application.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springbt_mybatis_sqlserver/src/main/resources/application.properties
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/main/resources/mapper/UserMapper.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | select * from user_test
14 |
15 |
16 |
17 | insert into user_test ( user_id, user_name, sex, created_time ) values ( #{userId}, #{userName}, #{sex}, #{createdTime} )
18 |
19 |
20 |
21 | delete from user_test where user_name = #{userName}
22 |
23 |
24 |
--------------------------------------------------------------------------------
/springbt_mybatis_sqlserver/src/test/java/cn/codesheep/springbt_mybatis_sqlserver/SpringbtMybatisSqlserverApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_mybatis_sqlserver;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtMybatisSqlserverApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_security_jwt/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | springbt_security_jwt
8 | 0.0.1
9 | jar
10 |
11 | springbt_security_jwt
12 | springbt_security_jwt
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.6.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 | org.springframework.boot
41 | spring-boot-starter-data-jpa
42 |
43 |
44 |
45 | org.springframework.boot
46 | spring-boot-starter-security
47 |
48 |
49 |
50 | mysql
51 | mysql-connector-java
52 | 5.1.40
53 |
54 |
55 |
56 | io.jsonwebtoken
57 | jjwt
58 | 0.9.0
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | org.springframework.boot
67 | spring-boot-maven-plugin
68 |
69 |
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/SpringbtSecurityJwtApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | /**
7 | * @www.codesheep.cn
8 | * 20190312
9 | */
10 | @SpringBootApplication
11 | public class SpringbtSecurityJwtApplication {
12 |
13 | public static void main(String[] args) {
14 | SpringApplication.run(SpringbtSecurityJwtApplication.class, args);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/comm/Const.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.comm;
2 |
3 | /**
4 | * @www.codesheep.cn
5 | * 20190312
6 | */
7 | public class Const {
8 |
9 | public static final long EXPIRATION_TIME = 432_000_000; // 5天(以毫秒ms计)
10 | public static final String SECRET = "CodeSheepSecret"; // JWT密码
11 | public static final String TOKEN_PREFIX = "Bearer"; // Token前缀
12 | public static final String HEADER_STRING = "Authorization"; // 存放Token的Header Key
13 | }
14 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/config/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.config;
2 |
3 | import cn.codesheep.springbt_security_jwt.filter.JwtTokenFilter;
4 | import cn.codesheep.springbt_security_jwt.service.UserService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.http.HttpMethod;
9 | import org.springframework.security.authentication.AuthenticationManager;
10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
11 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
13 | import org.springframework.security.config.annotation.web.builders.WebSecurity;
14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
16 | import org.springframework.security.config.http.SessionCreationPolicy;
17 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
18 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
19 |
20 | /**
21 | * @www.codesheep.cn
22 | * 20190312
23 | */
24 | @Configuration
25 | @EnableWebSecurity
26 | @EnableGlobalMethodSecurity(prePostEnabled=true)
27 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
28 |
29 | @Autowired
30 | private UserService userService;
31 |
32 | @Bean
33 | public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
34 | return new JwtTokenFilter();
35 | }
36 |
37 | @Bean
38 | public AuthenticationManager authenticationManagerBean() throws Exception {
39 | return super.authenticationManagerBean();
40 | }
41 |
42 | @Override
43 | protected void configure( AuthenticationManagerBuilder auth ) throws Exception {
44 | auth.userDetailsService( userService ).passwordEncoder( new BCryptPasswordEncoder() );
45 | }
46 |
47 | @Override
48 | protected void configure( HttpSecurity httpSecurity ) throws Exception {
49 |
50 | httpSecurity.csrf().disable()
51 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
52 | .authorizeRequests()
53 | .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
54 | .antMatchers(HttpMethod.POST, "/authentication/**").permitAll()
55 | .antMatchers(HttpMethod.POST).authenticated()
56 | .antMatchers(HttpMethod.PUT).authenticated()
57 | .antMatchers(HttpMethod.DELETE).authenticated()
58 | .antMatchers(HttpMethod.GET).authenticated();
59 |
60 | httpSecurity
61 | .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
62 | httpSecurity.headers().cacheControl();
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/controller/JwtAuthController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.controller;
2 |
3 | import cn.codesheep.springbt_security_jwt.model.entity.User;
4 | import cn.codesheep.springbt_security_jwt.service.AuthService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.security.core.AuthenticationException;
7 | import org.springframework.web.bind.annotation.RequestBody;
8 | import org.springframework.web.bind.annotation.RequestMapping;
9 | import org.springframework.web.bind.annotation.RequestMethod;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | /**
13 | * @www.codesheep.cn
14 | * 20190312
15 | */
16 | @RestController
17 | public class JwtAuthController {
18 |
19 | @Autowired
20 | private AuthService authService;
21 |
22 | // 登录
23 | @RequestMapping(value = "/authentication/login", method = RequestMethod.POST)
24 | public String createToken( String username,String password ) throws AuthenticationException {
25 | return authService.login( username, password );
26 | }
27 |
28 | // 注册
29 | @RequestMapping(value = "/authentication/register", method = RequestMethod.POST)
30 | public User register( @RequestBody User addedUser ) throws AuthenticationException {
31 | return authService.register(addedUser);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/controller/TestController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.controller;
2 |
3 | import org.springframework.security.access.prepost.PreAuthorize;
4 | import org.springframework.web.bind.annotation.RequestMapping;
5 | import org.springframework.web.bind.annotation.RequestMethod;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | /**
9 | * @www.codesheep.cn
10 | * 20190312
11 | */
12 | @RestController
13 | public class TestController {
14 |
15 | // 测试普通权限
16 | @PreAuthorize("hasAuthority('ROLE_NORMAL')")
17 | @RequestMapping( value="/normal/test", method = RequestMethod.GET )
18 | public String test1() {
19 | return "ROLE_NORMAL /normal/test接口调用成功!";
20 | }
21 |
22 | // 测试管理员权限
23 | @PreAuthorize("hasAuthority('ROLE_ADMIN')")
24 | @RequestMapping( value = "/admin/test", method = RequestMethod.GET )
25 | public String test2() {
26 | return "ROLE_ADMIN /admin/test接口调用成功!";
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/filter/JwtTokenFilter.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.filter;
2 |
3 | import cn.codesheep.springbt_security_jwt.comm.Const;
4 | import cn.codesheep.springbt_security_jwt.util.JwtTokenUtil;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.beans.factory.annotation.Value;
7 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8 | import org.springframework.security.core.context.SecurityContextHolder;
9 | import org.springframework.security.core.userdetails.UserDetails;
10 | import org.springframework.security.core.userdetails.UserDetailsService;
11 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
12 | import org.springframework.stereotype.Component;
13 | import org.springframework.web.filter.OncePerRequestFilter;
14 |
15 | import javax.servlet.FilterChain;
16 | import javax.servlet.ServletException;
17 | import javax.servlet.http.HttpServletRequest;
18 | import javax.servlet.http.HttpServletResponse;
19 | import java.io.IOException;
20 |
21 | /**
22 | * @www.codesheep.cn
23 | * 20190312
24 | */
25 | @Component
26 | public class JwtTokenFilter extends OncePerRequestFilter {
27 |
28 | @Autowired
29 | private UserDetailsService userDetailsService;
30 |
31 | @Autowired
32 | private JwtTokenUtil jwtTokenUtil;
33 |
34 | @Override
35 | protected void doFilterInternal ( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
36 |
37 | String authHeader = request.getHeader( Const.HEADER_STRING );
38 | if (authHeader != null && authHeader.startsWith( Const.TOKEN_PREFIX )) {
39 | final String authToken = authHeader.substring( Const.TOKEN_PREFIX.length() );
40 | String username = jwtTokenUtil.getUsernameFromToken(authToken);
41 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
42 | UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
43 | if (jwtTokenUtil.validateToken(authToken, userDetails)) {
44 | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
45 | userDetails, null, userDetails.getAuthorities());
46 | authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
47 | request));
48 | SecurityContextHolder.getContext().setAuthentication(authentication);
49 | }
50 | }
51 | }
52 | chain.doFilter(request, response);
53 | }
54 | }
55 |
56 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/model/entity/Role.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.model.entity;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.Id;
6 |
7 | /**
8 | * @www.codesheep.cn
9 | * 20190312
10 | */
11 | @Entity
12 | public class Role {
13 |
14 | @Id
15 | @GeneratedValue
16 | private Long id;
17 |
18 | private String name;
19 |
20 | public Long getId() {
21 | return id;
22 | }
23 |
24 | public void setId(Long id) {
25 | this.id = id;
26 | }
27 |
28 | public String getName() {
29 | return name;
30 | }
31 |
32 | public void setName(String name) {
33 | this.name = name;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/model/entity/User.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.model.entity;
2 |
3 | import org.springframework.security.core.GrantedAuthority;
4 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 |
7 | import javax.persistence.*;
8 | import java.util.ArrayList;
9 | import java.util.Collection;
10 | import java.util.List;
11 |
12 | /**
13 | * @www.codesheep.cn
14 | * 20190312
15 | */
16 | @Entity
17 | public class User implements UserDetails {
18 |
19 | @Id
20 | @GeneratedValue
21 | private Long id;
22 |
23 | private String username;
24 |
25 | private String password;
26 |
27 | @ManyToMany(cascade = {CascadeType.REFRESH},fetch = FetchType.EAGER)
28 | private List roles;
29 |
30 | public Long getId() {
31 | return id;
32 | }
33 |
34 | public void setId(Long id) {
35 | this.id = id;
36 | }
37 |
38 | public void setUsername(String username) {
39 | this.username = username;
40 | }
41 |
42 | public void setPassword(String password) {
43 | this.password = password;
44 | }
45 |
46 | public List getRoles() {
47 | return roles;
48 | }
49 |
50 | public void setRoles(List roles) {
51 | this.roles = roles;
52 | }
53 |
54 | // 下面为实现UserDetails而需要的重写方法!
55 |
56 | @Override
57 | public boolean isAccountNonExpired() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public boolean isAccountNonLocked() {
63 | return true;
64 | }
65 |
66 | @Override
67 | public boolean isCredentialsNonExpired() {
68 | return true;
69 | }
70 |
71 | @Override
72 | public boolean isEnabled() {
73 | return true;
74 | }
75 |
76 | @Override
77 | public Collection extends GrantedAuthority> getAuthorities() {
78 | List authorities = new ArrayList<>();
79 | for (Role role : roles) {
80 | authorities.add( new SimpleGrantedAuthority( role.getName() ) );
81 | }
82 | return authorities;
83 | }
84 |
85 | @Override
86 | public String getUsername() {
87 | return username;
88 | }
89 |
90 | @Override
91 | public String getPassword() {
92 | return password;
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/repository/UserRepository.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.repository;
2 |
3 | import cn.codesheep.springbt_security_jwt.model.entity.User;
4 | import org.springframework.data.jpa.repository.JpaRepository;
5 |
6 | /**
7 | * @www.codesheep.cn
8 | * 20190312
9 | */
10 | public interface UserRepository extends JpaRepository {
11 | User findByUsername( String username );
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/service/AuthService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.service;
2 |
3 | import cn.codesheep.springbt_security_jwt.model.entity.User;
4 |
5 | /**
6 | * @www.codesheep.cn
7 | * 20190312
8 | */
9 | public interface AuthService {
10 |
11 | User register( User userToAdd );
12 | String login( String username, String password );
13 | }
14 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/service/UserService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.service;
2 |
3 | import cn.codesheep.springbt_security_jwt.model.entity.Role;
4 | import cn.codesheep.springbt_security_jwt.model.entity.User;
5 | import cn.codesheep.springbt_security_jwt.repository.UserRepository;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.security.core.userdetails.UserDetails;
8 | import org.springframework.security.core.userdetails.UserDetailsService;
9 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
10 | import org.springframework.stereotype.Service;
11 |
12 | /**
13 | * @www.codesheep.cn
14 | * 20190312
15 | */
16 | @Service
17 | public class UserService implements UserDetailsService {
18 |
19 | @Autowired
20 | UserRepository userRepository;
21 |
22 | @Override
23 | public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
24 |
25 | User user = userRepository.findByUsername(s);
26 | if (user == null) {
27 | throw new UsernameNotFoundException("用户不存在");
28 | }
29 | return user;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/java/cn/codesheep/springbt_security_jwt/service/impl/AuthServiceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt.service.impl;
2 |
3 | import cn.codesheep.springbt_security_jwt.comm.Const;
4 | import cn.codesheep.springbt_security_jwt.model.entity.User;
5 | import cn.codesheep.springbt_security_jwt.repository.UserRepository;
6 | import cn.codesheep.springbt_security_jwt.service.AuthService;
7 | import cn.codesheep.springbt_security_jwt.util.JwtTokenUtil;
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.security.authentication.AuthenticationManager;
10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11 | import org.springframework.security.core.Authentication;
12 | import org.springframework.security.core.context.SecurityContextHolder;
13 | import org.springframework.security.core.userdetails.UserDetails;
14 | import org.springframework.security.core.userdetails.UserDetailsService;
15 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
16 | import org.springframework.stereotype.Service;
17 |
18 | /**
19 | * @www.codesheep.cn
20 | * 20190312
21 | */
22 | @Service
23 | public class AuthServiceImpl implements AuthService {
24 |
25 | @Autowired
26 | private AuthenticationManager authenticationManager;
27 |
28 | @Autowired
29 | private UserDetailsService userDetailsService;
30 |
31 | @Autowired
32 | private JwtTokenUtil jwtTokenUtil;
33 |
34 | @Autowired
35 | private UserRepository userRepository;
36 |
37 | // 登录
38 | @Override
39 | public String login( String username, String password ) {
40 |
41 | UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken( username, password );
42 |
43 | final Authentication authentication = authenticationManager.authenticate(upToken);
44 | SecurityContextHolder.getContext().setAuthentication(authentication);
45 |
46 | final UserDetails userDetails = userDetailsService.loadUserByUsername( username );
47 | final String token = jwtTokenUtil.generateToken(userDetails);
48 | return token;
49 | }
50 |
51 | // 注册
52 | @Override
53 | public User register( User userToAdd ) {
54 |
55 | final String username = userToAdd.getUsername();
56 | if( userRepository.findByUsername(username)!=null ) {
57 | return null;
58 | }
59 | BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
60 | final String rawPassword = userToAdd.getPassword();
61 | userToAdd.setPassword( encoder.encode(rawPassword) );
62 | return userRepository.save(userToAdd);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=9991
2 |
3 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
4 | spring.datasource.url=jdbc:mysql://121.196.XXX.XXX:3306/spring_security_jwt?useUnicode=true&characterEncoding=utf-8
5 | spring.datasource.username=root
6 | spring.datasource.password=XXXXXX
7 |
8 | logging.level.org.springframework.security=info
9 |
10 | spring.jpa.hibernate.ddl-auto=update
11 | spring.jpa.show-sql=true
12 | spring.jackson.serialization.indent_output=true
13 |
--------------------------------------------------------------------------------
/springbt_security_jwt/src/test/java/cn/codesheep/springbt_security_jwt/SpringbtSecurityJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_security_jwt;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtSecurityJwtApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client1/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springbt_sso_jwt
7 | cn.codesheep
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | codesheep-client1
13 |
14 |
15 |
16 | org.springframework.cloud
17 | spring-cloud-starter-oauth2
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client1/src/main/java/cn/codesheep/Client1Application.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Client1Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Client1Application.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client1/src/main/java/cn/codesheep/config/ClientWebsecurityConfigurer.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.config;
2 |
3 |
4 | import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10 |
11 | @Configuration
12 | @EnableWebSecurity
13 | @EnableGlobalMethodSecurity(prePostEnabled = true)
14 | @EnableOAuth2Sso
15 | public class ClientWebsecurityConfigurer extends WebSecurityConfigurerAdapter {
16 |
17 | @Override
18 | public void configure(HttpSecurity http) throws Exception {
19 | http.antMatcher("/**").authorizeRequests()
20 | .anyRequest().authenticated();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client1/src/main/java/cn/codesheep/controller/TestController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.controller;
2 |
3 | import org.springframework.security.access.prepost.PreAuthorize;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 | import org.springframework.web.bind.annotation.RestController;
6 |
7 | @RestController
8 | public class TestController {
9 |
10 | @GetMapping("/normal")
11 | @PreAuthorize("hasAuthority('ROLE_NORMAL')")
12 | public String normal( ) {
13 | return "normal permission test success !!!";
14 | }
15 |
16 | @GetMapping("/medium")
17 | @PreAuthorize("hasAuthority('ROLE_MEDIUM')")
18 | public String medium() {
19 | return "medium permission test success !!!";
20 | }
21 |
22 | @GetMapping("/admin")
23 | @PreAuthorize("hasAuthority('ROLE_ADMIN')")
24 | public String admin() {
25 | return "admin permission test success !!!";
26 | }
27 | }
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client1/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | auth-server: http://localhost:8085/uac
2 | server:
3 | port: 8086
4 |
5 | security:
6 | oauth2:
7 | client:
8 | client-id: sheep1
9 | client-secret: 123456
10 | user-authorization-uri: ${auth-server}/oauth/authorize
11 | access-token-uri: ${auth-server}/oauth/token
12 | resource:
13 | jwt:
14 | key-uri: ${auth-server}/oauth/token_key
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client2/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springbt_sso_jwt
7 | cn.codesheep
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | codesheep-client2
13 |
14 |
15 |
16 | org.springframework.cloud
17 | spring-cloud-starter-oauth2
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client2/src/main/java/cn/codesheep/Client2Application.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class Client2Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(Client2Application.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client2/src/main/java/cn/codesheep/config/ClientWebsecurityConfigurer.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.config;
2 |
3 |
4 | import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10 |
11 | @Configuration
12 | @EnableWebSecurity
13 | @EnableGlobalMethodSecurity(prePostEnabled = true)
14 | @EnableOAuth2Sso
15 | public class ClientWebsecurityConfigurer extends WebSecurityConfigurerAdapter {
16 |
17 | @Override
18 | public void configure(HttpSecurity http) throws Exception {
19 | http.antMatcher("/**").authorizeRequests()
20 | .anyRequest().authenticated();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client2/src/main/java/cn/codesheep/controller/TestController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.controller;
2 |
3 | import org.springframework.security.access.prepost.PreAuthorize;
4 | import org.springframework.web.bind.annotation.GetMapping;
5 | import org.springframework.web.bind.annotation.RestController;
6 |
7 | @RestController
8 | public class TestController {
9 |
10 | @GetMapping("/normal")
11 | @PreAuthorize("hasAuthority('ROLE_NORMAL')")
12 | public String normal( ) {
13 | return "normal permission test success !!!";
14 | }
15 |
16 | @GetMapping("/medium")
17 | @PreAuthorize("hasAuthority('ROLE_MEDIUM')")
18 | public String medium() {
19 | return "medium permission test success !!!";
20 | }
21 |
22 | @GetMapping("/admin")
23 | @PreAuthorize("hasAuthority('ROLE_ADMIN')")
24 | public String admin() {
25 | return "admin permission test success !!!";
26 | }
27 | }
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-client2/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | auth-server: http://localhost:8085/uac
2 | server:
3 | port: 8087
4 |
5 | security:
6 | oauth2:
7 | client:
8 | client-id: sheep2
9 | client-secret: 123456
10 | user-authorization-uri: ${auth-server}/oauth/authorize
11 | access-token-uri: ${auth-server}/oauth/token
12 | resource:
13 | jwt:
14 | key-uri: ${auth-server}/oauth/token_key
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-server/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springbt_sso_jwt
7 | cn.codesheep
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | codesheep-server
13 |
14 |
15 |
16 | org.apache.maven.plugins
17 | maven-compiler-plugin
18 |
19 | 6
20 | 6
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 | org.springframework.cloud
29 | spring-cloud-starter-oauth2
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-server/src/main/java/cn/codesheep/ServerApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
6 |
7 | @SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
8 | public class ServerApplication {
9 |
10 | public static void main(String[] args) {
11 | SpringApplication.run(ServerApplication.class, args);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-server/src/main/java/cn/codesheep/config/SpringSecurityConfig.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.config;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.context.annotation.Bean;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.authentication.AuthenticationManager;
7 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11 | import org.springframework.security.core.userdetails.UserDetailsService;
12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
13 | import org.springframework.security.crypto.password.PasswordEncoder;
14 |
15 | @Configuration
16 | public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
17 |
18 | @Override
19 | @Bean
20 | public AuthenticationManager authenticationManager() throws Exception {
21 | return super.authenticationManager();
22 | }
23 |
24 | @Autowired
25 | private UserDetailsService userDetailsService;
26 |
27 | @Bean
28 | public PasswordEncoder passwordEncoder() {
29 | return new BCryptPasswordEncoder();
30 | }
31 |
32 | @Bean
33 | public DaoAuthenticationProvider authenticationProvider() {
34 | DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
35 | authenticationProvider.setUserDetailsService(userDetailsService);
36 | authenticationProvider.setPasswordEncoder(passwordEncoder());
37 | authenticationProvider.setHideUserNotFoundExceptions(false);
38 | return authenticationProvider;
39 | }
40 |
41 | @Override
42 | protected void configure(HttpSecurity http) throws Exception {
43 |
44 | http
45 | .requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**")
46 | .and()
47 | .authorizeRequests()
48 | .antMatchers("/oauth/**").authenticated()
49 | .and()
50 | .formLogin().permitAll();
51 | }
52 |
53 | @Override
54 | protected void configure(AuthenticationManagerBuilder auth) throws Exception {
55 | auth.authenticationProvider(authenticationProvider());
56 | }
57 |
58 | }
59 |
60 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-server/src/main/java/cn/codesheep/service/SheepUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.service;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.security.core.authority.AuthorityUtils;
5 | import org.springframework.security.core.userdetails.UserDetails;
6 | import org.springframework.security.core.userdetails.UserDetailsService;
7 | import org.springframework.security.core.userdetails.User;
8 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.stereotype.Component;
11 |
12 | @Component
13 | public class SheepUserDetailsService implements UserDetailsService {
14 |
15 | @Autowired
16 | private PasswordEncoder passwordEncoder;
17 |
18 | @Override
19 | public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
20 |
21 | if( !"codesheep".equals(s) )
22 | throw new UsernameNotFoundException("用户" + s + "不存在" );
23 |
24 | return new User( s, passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_NORMAL,ROLE_MEDIUM"));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/codesheep-server/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8085
3 | servlet:
4 | context-path: /uac
5 |
--------------------------------------------------------------------------------
/springbt_sso_jwt/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | cn.codesheep
8 | springbt_sso_jwt
9 | 1.0-SNAPSHOT
10 |
11 |
12 | codesheep-server
13 | codesheep-client1
14 | codesheep-client2
15 |
16 |
17 | pom
18 |
19 |
20 |
21 |
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-dependencies
26 | 2.0.8.RELEASE
27 | pom
28 | import
29 |
30 |
31 |
32 | io.spring.platform
33 | platform-bom
34 | Cairo-RELEASE
35 | pom
36 | import
37 |
38 |
39 |
40 | org.springframework.cloud
41 | spring-cloud-dependencies
42 | Finchley.SR2
43 | pom
44 | import
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/springbt_uid_generator/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | cn.codesheep
8 | springbt_uid_generator
9 | pom
10 | 1.0
11 |
12 | uid-generator
13 | uid-consumer
14 |
15 |
16 |
17 | org.springframework.boot
18 | spring-boot-starter-parent
19 | 2.0.6.RELEASE
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | springbt_uid_generator
7 | cn.codesheep
8 | 1.0
9 |
10 | 4.0.0
11 |
12 | uid-consumer
13 |
14 |
15 |
16 | UTF-8
17 | UTF-8
18 | 1.8
19 |
20 |
21 |
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-web
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-test
31 | test
32 |
33 |
34 |
35 | org.mybatis.spring.boot
36 | mybatis-spring-boot-starter
37 | 1.3.2
38 |
39 |
40 |
41 |
42 | mysql
43 | mysql-connector-java
44 | runtime
45 | 8.0.12
46 |
47 |
48 |
49 |
50 | com.alibaba
51 | druid-spring-boot-starter
52 | 1.1.9
53 |
54 |
55 |
56 |
57 | cn.codesheep
58 | uid-generator
59 | 1.0
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | org.springframework.boot
68 | spring-boot-maven-plugin
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/java/cn/codesheep/UidConsumerApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep;
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({"cn.codesheep","com.baidu.fsg.uid.worker.dao"})
9 | public class UidConsumerApplication {
10 |
11 | public static void main(String[] args) {
12 | SpringApplication.run(UidConsumerApplication.class,args);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/java/cn/codesheep/config/UidConfig.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.config;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.context.annotation.ImportResource;
5 |
6 | @Configuration
7 | @ImportResource(locations = { "classpath:uid/cached-uid-spring.xml" })
8 | public class UidConfig {
9 | }
10 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/java/cn/codesheep/controller/UidTestController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.controller;
2 |
3 | import cn.codesheep.service.UidGenService;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.web.bind.annotation.GetMapping;
6 | import org.springframework.web.bind.annotation.RestController;
7 |
8 | @RestController
9 | public class UidTestController {
10 |
11 | @Autowired
12 | private UidGenService uidGenService;
13 |
14 | @GetMapping("/testuid")
15 | public String test() {
16 |
17 | return String.valueOf(uidGenService.getUid());
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/java/cn/codesheep/service/UidGenService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.service;
2 |
3 | import com.baidu.fsg.uid.UidGenerator;
4 | import org.springframework.stereotype.Service;
5 |
6 | import javax.annotation.Resource;
7 |
8 | @Service
9 | public class UidGenService {
10 |
11 | @Resource
12 | private UidGenerator uidGenerator;
13 |
14 | public long getUid() {
15 | return uidGenerator.getUID();
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=9999
2 |
3 | # Mysql 数据源配置
4 | spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
5 | spring.datasource.username=root
6 | spring.datasource.password=xxxxxx
7 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver
8 |
9 | # 初始化时建立物理连接的个数
10 | spring.datasource.druid.initial-size=5
11 |
12 | # 最大连接池数量
13 | spring.datasource.druid.max-active=30
14 |
15 | # 最小连接池数量
16 | spring.datasource.druid.min-idle=5
17 |
18 | # 获取连接时最大等待时间,单位毫秒
19 | spring.datasource.druid.max-wait=60000
20 |
21 | # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
22 | spring.datasource.druid.time-between-eviction-runs-millis=60000
23 |
24 | # 连接保持空闲而不被驱逐的最小时间
25 | spring.datasource.druid.min-evictable-idle-time-millis=300000
26 |
27 | # 用来检测连接是否有效的sql,要求是一个查询语句
28 | spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
29 |
30 | # 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
31 | spring.datasource.druid.test-while-idle=true
32 |
33 | # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
34 | spring.datasource.druid.test-on-borrow=false
35 |
36 | # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
37 | spring.datasource.druid.test-on-return=false
38 |
39 | # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
40 | spring.datasource.druid.pool-prepared-statements=true
41 |
42 | # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。
43 | spring.datasource.druid.max-pool-prepared-statement-per-connection-size=50
44 |
45 | # 配置监控统计拦截的filters,去掉后监控界面sql无法统计
46 | spring.datasource.druid.filters=stat,wall
47 |
48 | # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
49 | spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
50 |
51 | # 合并多个DruidDataSource的监控数据
52 | spring.datasource.druid.use-global-data-source-stat=true
53 |
54 |
55 | # 关于Druid可视化界面登录的权限控制
56 | spring.datasource.druid.stat-view-servlet.login-username=admin
57 | spring.datasource.druid.stat-view-servlet.login-password=123
58 | spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
59 |
60 |
61 | # mybatis配置
62 | mybatis.mapper-locations=classpath:mapper/*.xml
63 | mybatis.configuration.map-underscore-to-camel-case=true
64 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/resources/mapper/WORKER_NODE.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
17 | INSERT INTO WORKER_NODE
18 | (HOST_NAME,
19 | PORT,
20 | TYPE,
21 | LAUNCH_DATE,
22 | MODIFIED,
23 | CREATED)
24 | VALUES (
25 | #{hostName},
26 | #{port},
27 | #{type},
28 | #{launchDate},
29 | NOW(),
30 | NOW())
31 |
32 |
33 |
34 | SELECT
35 | ID,
36 | HOST_NAME,
37 | PORT,
38 | TYPE,
39 | LAUNCH_DATE,
40 | MODIFIED,
41 | CREATED
42 | FROM
43 | WORKER_NODE
44 | WHERE
45 | HOST_NAME = #{host} AND PORT = #{port}
46 |
47 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-consumer/src/main/resources/uid/cached-uid-spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/UidGenerator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid;
17 |
18 | import com.baidu.fsg.uid.exception.UidGenerateException;
19 |
20 | /**
21 | * Represents a unique id generator.
22 | *
23 | * @author yutianbao
24 | */
25 | public interface UidGenerator {
26 |
27 | /**
28 | * Get a unique ID
29 | *
30 | * @return UID
31 | * @throws UidGenerateException
32 | */
33 | long getUID() throws UidGenerateException;
34 |
35 | /**
36 | * Parse the UID into elements which are used to generate the UID.
37 | * Such as timestamp & workerId & sequence...
38 | *
39 | * @param uid
40 | * @return Parsed info
41 | */
42 | String parseUID(long uid);
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/buffer/BufferedUidProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.buffer;
17 |
18 | import java.util.List;
19 |
20 | /**
21 | * Buffered UID provider(Lambda supported), which provides UID in the same one second
22 | *
23 | * @author yutianbao
24 | */
25 | @FunctionalInterface
26 | public interface BufferedUidProvider {
27 |
28 | /**
29 | * Provides UID in one second
30 | *
31 | * @param momentInSecond
32 | * @return
33 | */
34 | List provide(long momentInSecond);
35 | }
36 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/buffer/RejectedPutBufferHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.buffer;
17 |
18 | /**
19 | * If tail catches the cursor it means that the ring buffer is full, any more buffer put request will be rejected.
20 | * Specify the policy to handle the reject. This is a Lambda supported interface
21 | *
22 | * @author yutianbao
23 | */
24 | @FunctionalInterface
25 | public interface RejectedPutBufferHandler {
26 |
27 | /**
28 | * Reject put buffer request
29 | *
30 | * @param ringBuffer
31 | * @param uid
32 | */
33 | void rejectPutBuffer(RingBuffer ringBuffer, long uid);
34 | }
35 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/buffer/RejectedTakeBufferHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.buffer;
17 |
18 | /**
19 | * If cursor catches the tail it means that the ring buffer is empty, any more buffer take request will be rejected.
20 | * Specify the policy to handle the reject. This is a Lambda supported interface
21 | *
22 | * @author yutianbao
23 | */
24 | @FunctionalInterface
25 | public interface RejectedTakeBufferHandler {
26 |
27 | /**
28 | * Reject take buffer request
29 | *
30 | * @param ringBuffer
31 | */
32 | void rejectTakeBuffer(RingBuffer ringBuffer);
33 | }
34 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/exception/UidGenerateException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.exception;
17 |
18 | /**
19 | * UidGenerateException
20 | *
21 | * @author yutianbao
22 | */
23 | public class UidGenerateException extends RuntimeException {
24 |
25 | /**
26 | * Serial Version UID
27 | */
28 | private static final long serialVersionUID = -27048199131316992L;
29 |
30 | /**
31 | * Default constructor
32 | */
33 | public UidGenerateException() {
34 | super();
35 | }
36 |
37 | /**
38 | * Constructor with message & cause
39 | *
40 | * @param message
41 | * @param cause
42 | */
43 | public UidGenerateException(String message, Throwable cause) {
44 | super(message, cause);
45 | }
46 |
47 | /**
48 | * Constructor with message
49 | *
50 | * @param message
51 | */
52 | public UidGenerateException(String message) {
53 | super(message);
54 | }
55 |
56 | /**
57 | * Constructor with message format
58 | *
59 | * @param msgFormat
60 | * @param args
61 | */
62 | public UidGenerateException(String msgFormat, Object... args) {
63 | super(String.format(msgFormat, args));
64 | }
65 |
66 | /**
67 | * Constructor with cause
68 | *
69 | * @param cause
70 | */
71 | public UidGenerateException(Throwable cause) {
72 | super(cause);
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/utils/EnumUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.utils;
17 |
18 | import org.springframework.util.Assert;
19 |
20 | /**
21 | * EnumUtils provides the operations for {@link ValuedEnum} such as Parse, value of...
22 | *
23 | * @author yutianbao
24 | */
25 | public abstract class EnumUtils {
26 |
27 | /**
28 | * Parse the bounded value into ValuedEnum
29 | *
30 | * @param clz
31 | * @param value
32 | * @return
33 | */
34 | public static , V> T parse(Class clz, V value) {
35 | Assert.notNull(clz, "clz can not be null");
36 | if (value == null) {
37 | return null;
38 | }
39 |
40 | for (T t : clz.getEnumConstants()) {
41 | if (value.equals(t.value())) {
42 | return t;
43 | }
44 | }
45 | return null;
46 | }
47 |
48 | /**
49 | * Null-safe valueOf function
50 | *
51 | * @param
52 | * @param enumType
53 | * @param name
54 | * @return
55 | */
56 | public static > T valueOf(Class enumType, String name) {
57 | if (name == null) {
58 | return null;
59 | }
60 |
61 | return Enum.valueOf(enumType, name);
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/utils/NetUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.utils;
17 |
18 | import java.net.InetAddress;
19 | import java.net.NetworkInterface;
20 | import java.net.SocketException;
21 | import java.util.Enumeration;
22 |
23 | /**
24 | * NetUtils
25 | *
26 | * @author yutianbao
27 | */
28 | public abstract class NetUtils {
29 |
30 | /**
31 | * Pre-loaded local address
32 | */
33 | public static InetAddress localAddress;
34 |
35 | static {
36 | try {
37 | localAddress = getLocalInetAddress();
38 | } catch (SocketException e) {
39 | throw new RuntimeException("fail to get local ip.");
40 | }
41 | }
42 |
43 | /**
44 | * Retrieve the first validated local ip address(the Public and LAN ip addresses are validated).
45 | *
46 | * @return the local address
47 | * @throws SocketException the socket exception
48 | */
49 | public static InetAddress getLocalInetAddress() throws SocketException {
50 | // enumerates all network interfaces
51 | Enumeration enu = NetworkInterface.getNetworkInterfaces();
52 |
53 | while (enu.hasMoreElements()) {
54 | NetworkInterface ni = enu.nextElement();
55 | if (ni.isLoopback()) {
56 | continue;
57 | }
58 |
59 | Enumeration addressEnumeration = ni.getInetAddresses();
60 | while (addressEnumeration.hasMoreElements()) {
61 | InetAddress address = addressEnumeration.nextElement();
62 |
63 | // ignores all invalidated addresses
64 | if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) {
65 | continue;
66 | }
67 |
68 | return address;
69 | }
70 | }
71 |
72 | throw new RuntimeException("No validated local address!");
73 | }
74 |
75 | /**
76 | * Retrieve local address
77 | *
78 | * @return the string local address
79 | */
80 | public static String getLocalAddress() {
81 | return localAddress.getHostAddress();
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/utils/PaddedAtomicLong.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.utils;
17 |
18 | import java.util.concurrent.atomic.AtomicLong;
19 |
20 | /**
21 | * Represents a padded {@link AtomicLong} to prevent the FalseSharing problem
22 | *
23 | * The CPU cache line commonly be 64 bytes, here is a sample of cache line after padding:
24 | * 64 bytes = 8 bytes (object reference) + 6 * 8 bytes (padded long) + 8 bytes (a long value)
25 | *
26 | * @author yutianbao
27 | */
28 | public class PaddedAtomicLong extends AtomicLong {
29 | private static final long serialVersionUID = -3415778863941386253L;
30 |
31 | /** Padded 6 long (48 bytes) */
32 | public volatile long p1, p2, p3, p4, p5, p6 = 7L;
33 |
34 | /**
35 | * Constructors from {@link AtomicLong}
36 | */
37 | public PaddedAtomicLong() {
38 | super();
39 | }
40 |
41 | public PaddedAtomicLong(long initialValue) {
42 | super(initialValue);
43 | }
44 |
45 | /**
46 | * To prevent GC optimizations for cleaning unused padded references
47 | */
48 | public long sumPaddingToPreventOptimization() {
49 | return p1 + p2 + p3 + p4 + p5 + p6;
50 | }
51 |
52 | }
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/utils/ValuedEnum.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.utils;
17 |
18 | /**
19 | * {@code ValuedEnum} defines an enumeration which is bounded to a value, you
20 | * may implements this interface when you defines such kind of enumeration, that
21 | * you can use {@link EnumUtils} to simplify parse and valueOf operation.
22 | *
23 | * @author yutianbao
24 | */
25 | public interface ValuedEnum {
26 | T value();
27 | }
28 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/worker/DisposableWorkerIdAssigner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker;
17 |
18 | import com.baidu.fsg.uid.utils.DockerUtils;
19 | import com.baidu.fsg.uid.utils.NetUtils;
20 | import com.baidu.fsg.uid.worker.dao.WorkerNodeDAO;
21 | import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity;
22 | import org.apache.commons.lang.math.RandomUtils;
23 | import org.slf4j.Logger;
24 | import org.slf4j.LoggerFactory;
25 | import org.springframework.transaction.annotation.Transactional;
26 |
27 | import javax.annotation.Resource;
28 |
29 | /**
30 | * Represents an implementation of {@link WorkerIdAssigner},
31 | * the worker id will be discarded after assigned to the UidGenerator
32 | *
33 | * @author yutianbao
34 | */
35 | public class DisposableWorkerIdAssigner implements WorkerIdAssigner {
36 | private static final Logger LOGGER = LoggerFactory.getLogger(DisposableWorkerIdAssigner.class);
37 |
38 | @Resource
39 | private WorkerNodeDAO workerNodeDAO;
40 |
41 | /**
42 | * Assign worker id base on database.
43 | * If there is host name & port in the environment, we considered that the node runs in Docker container
44 | * Otherwise, the node runs on an actual machine.
45 | *
46 | * @return assigned worker id
47 | */
48 | @Transactional
49 | public long assignWorkerId() {
50 | // build worker node entity
51 | WorkerNodeEntity workerNodeEntity = buildWorkerNode();
52 |
53 | // add worker node for new (ignore the same IP + PORT)
54 | workerNodeDAO.addWorkerNode(workerNodeEntity);
55 | LOGGER.info("Add worker node:" + workerNodeEntity);
56 |
57 | return workerNodeEntity.getId();
58 | }
59 |
60 | /**
61 | * Build worker node entity by IP and PORT
62 | */
63 | private WorkerNodeEntity buildWorkerNode() {
64 | WorkerNodeEntity workerNodeEntity = new WorkerNodeEntity();
65 | if (DockerUtils.isDocker()) {
66 | workerNodeEntity.setType(WorkerNodeType.CONTAINER.value());
67 | workerNodeEntity.setHostName(DockerUtils.getDockerHost());
68 | workerNodeEntity.setPort(DockerUtils.getDockerPort());
69 |
70 | } else {
71 | workerNodeEntity.setType(WorkerNodeType.ACTUAL.value());
72 | workerNodeEntity.setHostName(NetUtils.getLocalAddress());
73 | workerNodeEntity.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
74 | }
75 |
76 | return workerNodeEntity;
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/worker/WorkerIdAssigner.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker;
17 |
18 | /**
19 | * Represents a worker id assigner for {@link com.baidu.fsg.uid.impl.DefaultUidGenerator}
20 | *
21 | * @author yutianbao
22 | */
23 | public interface WorkerIdAssigner {
24 |
25 | /**
26 | * Assign worker id for {@link com.baidu.fsg.uid.impl.DefaultUidGenerator}
27 | *
28 | * @return assigned worker id
29 | */
30 | long assignWorkerId();
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/worker/WorkerNodeType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker;
17 |
18 | import com.baidu.fsg.uid.utils.ValuedEnum;
19 |
20 | /**
21 | * WorkerNodeType
22 | *
CONTAINER: Such as Docker
23 | * ACTUAL: Actual machine
24 | *
25 | * @author yutianbao
26 | */
27 | public enum WorkerNodeType implements ValuedEnum {
28 |
29 | CONTAINER(1), ACTUAL(2);
30 |
31 | /**
32 | * Lock type
33 | */
34 | private final Integer type;
35 |
36 | /**
37 | * Constructor with field of type
38 | */
39 | private WorkerNodeType(Integer type) {
40 | this.type = type;
41 | }
42 |
43 | @Override
44 | public Integer value() {
45 | return type;
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/worker/dao/WorkerNodeDAO.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker.dao;
17 |
18 | import com.baidu.fsg.uid.worker.entity.WorkerNodeEntity;
19 | import org.apache.ibatis.annotations.Param;
20 | import org.springframework.stereotype.Repository;
21 |
22 | /**
23 | * DAO for M_WORKER_NODE
24 | *
25 | * @author yutianbao
26 | */
27 | @Repository
28 | public interface WorkerNodeDAO {
29 |
30 | /**
31 | * Get {@link WorkerNodeEntity} by node host
32 | *
33 | * @param host
34 | * @param port
35 | * @return
36 | */
37 | WorkerNodeEntity getWorkerNodeByHostPort(@Param("host") String host, @Param("port") String port);
38 |
39 | /**
40 | * Add {@link WorkerNodeEntity}
41 | *
42 | * @param workerNodeEntity
43 | */
44 | void addWorkerNode(WorkerNodeEntity workerNodeEntity);
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/java/com/baidu/fsg/uid/worker/entity/WorkerNodeEntity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.baidu.fsg.uid.worker.entity;
17 |
18 | import java.util.Date;
19 |
20 | import org.apache.commons.lang.builder.ReflectionToStringBuilder;
21 | import org.apache.commons.lang.builder.ToStringStyle;
22 |
23 | import com.baidu.fsg.uid.worker.WorkerNodeType;
24 |
25 | /**
26 | * Entity for M_WORKER_NODE
27 | *
28 | * @author yutianbao
29 | */
30 | public class WorkerNodeEntity {
31 |
32 | /**
33 | * Entity unique id (table unique)
34 | */
35 | private long id;
36 |
37 | /**
38 | * Type of CONTAINER: HostName, ACTUAL : IP.
39 | */
40 | private String hostName;
41 |
42 | /**
43 | * Type of CONTAINER: Port, ACTUAL : Timestamp + Random(0-10000)
44 | */
45 | private String port;
46 |
47 | /**
48 | * type of {@link WorkerNodeType}
49 | */
50 | private int type;
51 |
52 | /**
53 | * Worker launch date, default now
54 | */
55 | private Date launchDate = new Date();
56 |
57 | /**
58 | * Created time
59 | */
60 | private Date created;
61 |
62 | /**
63 | * Last modified
64 | */
65 | private Date modified;
66 |
67 | /**
68 | * Getters & Setters
69 | */
70 | public long getId() {
71 | return id;
72 | }
73 |
74 | public void setId(long id) {
75 | this.id = id;
76 | }
77 |
78 | public String getHostName() {
79 | return hostName;
80 | }
81 |
82 | public void setHostName(String hostName) {
83 | this.hostName = hostName;
84 | }
85 |
86 | public String getPort() {
87 | return port;
88 | }
89 |
90 | public void setPort(String port) {
91 | this.port = port;
92 | }
93 |
94 | public int getType() {
95 | return type;
96 | }
97 |
98 | public void setType(int type) {
99 | this.type = type;
100 | }
101 |
102 | public Date getLaunchDate() {
103 | return launchDate;
104 | }
105 |
106 | public void setLaunchDateDate(Date launchDate) {
107 | this.launchDate = launchDate;
108 | }
109 |
110 | public Date getCreated() {
111 | return created;
112 | }
113 |
114 | public void setCreated(Date created) {
115 | this.created = created;
116 | }
117 |
118 | public Date getModified() {
119 | return modified;
120 | }
121 |
122 | public void setModified(Date modified) {
123 | this.modified = modified;
124 | }
125 |
126 | @Override
127 | public String toString() {
128 | return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
129 | }
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/resources/META-INF/mybatis/mapper/WORKER_NODE.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
17 | INSERT INTO WORKER_NODE
18 | (HOST_NAME,
19 | PORT,
20 | TYPE,
21 | LAUNCH_DATE,
22 | MODIFIED,
23 | CREATED)
24 | VALUES (
25 | #{hostName},
26 | #{port},
27 | #{type},
28 | #{launchDate},
29 | NOW(),
30 | NOW())
31 |
32 |
33 |
34 | SELECT
35 | ID,
36 | HOST_NAME,
37 | PORT,
38 | TYPE,
39 | LAUNCH_DATE,
40 | MODIFIED,
41 | CREATED
42 | FROM
43 | WORKER_NODE
44 | WHERE
45 | HOST_NAME = #{host} AND PORT = #{port}
46 |
47 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/main/scripts/WORKER_NODE.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE IF EXISTS WORKER_NODE;
2 | CREATE TABLE WORKER_NODE
3 | (
4 | ID BIGINT NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
5 | HOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name',
6 | PORT VARCHAR(64) NOT NULL COMMENT 'port',
7 | TYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER',
8 | LAUNCH_DATE DATE NOT NULL COMMENT 'launch date',
9 | MODIFIED TIMESTAMP NOT NULL COMMENT 'modified time',
10 | CREATED TIMESTAMP NOT NULL COMMENT 'created time',
11 | PRIMARY KEY(ID)
12 | )
13 | COMMENT='DB WorkerID Assigner for UID Generator',ENGINE = INNODB;
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/test/resources/uid/cached-uid-spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/test/resources/uid/default-uid-spring.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/springbt_uid_generator/uid-generator/src/test/resources/uid/mysql.properties:
--------------------------------------------------------------------------------
1 | #datasource db info
2 | mysql.driver=com.mysql.jdbc.Driver
3 | jdbc.url=jdbc:mysql://121.196.213.145:3306/demo
4 | jdbc.username=root
5 | jdbc.password=111111
6 | jdbc.maxActive=2
7 |
8 | #datasource base
9 | datasource.defaultAutoCommit=true
10 | datasource.initialSize=2
11 | datasource.minIdle=0
12 | datasource.maxWait=5000
13 | datasource.testWhileIdle=true
14 | datasource.testOnBorrow=true
15 | datasource.testOnReturn=false
16 | datasource.validationQuery=SELECT 1 FROM DUAL
17 | datasource.timeBetweenEvictionRunsMillis=30000
18 | datasource.minEvictableIdleTimeMillis=60000
19 | datasource.logAbandoned=true
20 | datasource.removeAbandoned=true
21 | datasource.removeAbandonedTimeout=120
22 | datasource.filters=stat
23 |
24 |
--------------------------------------------------------------------------------
/springbt_vesta/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | springbt_vesta
8 | 0.0.1
9 | jar
10 |
11 | springbt_vesta
12 | springbt_vesta
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.6.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 | com.robert.vesta
41 | vesta-service
42 | 0.0.1
43 |
44 |
45 |
46 | com.robert.vesta
47 | vesta-intf
48 | 0.0.1
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | org.springframework.boot
57 | spring-boot-maven-plugin
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/springbt_vesta/src/main/java/cn/codesheep/springbt_vesta/SpringbtVestaApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_vesta;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringbtVestaApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringbtVestaApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_vesta/src/main/java/cn/codesheep/springbt_vesta/config/UidConfig.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_vesta.config;
2 |
3 | import org.springframework.context.annotation.Configuration;
4 | import org.springframework.context.annotation.ImportResource;
5 |
6 | @Configuration
7 | @ImportResource( locations = { "classpath:ext/vesta/vesta-rest-main.xml" } )
8 | public class UidConfig {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/springbt_vesta/src/main/java/cn/codesheep/springbt_vesta/controller/UidController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_vesta.controller;
2 |
3 | import cn.codesheep.springbt_vesta.service.UidService;
4 | import com.robert.vesta.service.bean.Id;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.RequestMapping;
7 | import org.springframework.web.bind.annotation.RequestParam;
8 | import org.springframework.web.bind.annotation.RestController;
9 |
10 | @RestController
11 | public class UidController {
12 |
13 | @Autowired
14 | private UidService uidService;
15 |
16 | @RequestMapping("/genid")
17 | public long genId() {
18 | return uidService.genId();
19 | }
20 |
21 | @RequestMapping("/expid")
22 | public Id explainId(@RequestParam(value = "id", defaultValue = "0") long id) {
23 | return uidService.explainId( id );
24 | }
25 |
26 | @RequestMapping("/transtime")
27 | public String transTime( @RequestParam(value = "time", defaultValue = "-1") long time ) {
28 | return uidService.transTime(time);
29 | }
30 |
31 | @RequestMapping("/makeid")
32 | public long makeId(
33 | @RequestParam(value = "version", defaultValue = "-1") long version,
34 | @RequestParam(value = "type", defaultValue = "-1") long type,
35 | @RequestParam(value = "genMethod", defaultValue = "-1") long genMethod,
36 | @RequestParam(value = "machine", defaultValue = "-1") long machine,
37 | @RequestParam(value = "time", defaultValue = "-1") long time,
38 | @RequestParam(value = "seq", defaultValue = "-1") long seq) {
39 |
40 | return uidService.makeId( version, type, genMethod, machine, time, seq );
41 | }
42 | }
--------------------------------------------------------------------------------
/springbt_vesta/src/main/java/cn/codesheep/springbt_vesta/service/UidService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_vesta.service;
2 |
3 | import com.robert.vesta.service.bean.Id;
4 | import com.robert.vesta.service.intf.IdService;
5 | import org.springframework.stereotype.Service;
6 | import javax.annotation.Resource;
7 |
8 | @Service
9 | public class UidService {
10 |
11 | @Resource
12 | private IdService idService;
13 |
14 | // 若没有建立UidConfig类来专门引入ext/vesta/vesta-rest-main.xml文件,则用下面这种方式来手工获取bean也是可以的!!!
15 | // public UidService() {
16 | // ApplicationContext ac = new ClassPathXmlApplicationContext(
17 | // "ext/vesta/vesta-rest-main.xml");
18 | //
19 | // idService = (IdService) ac.getBean("idService");
20 | // }
21 |
22 | public long genId() {
23 | return idService.genId();
24 | }
25 |
26 | public Id explainId( long id ) {
27 | return idService.expId(id);
28 | }
29 |
30 | public String transTime( long time ) {
31 | return idService.transTime(time).toString();
32 | }
33 |
34 | public long makeId( long version, long type, long genMethod, long machine, long time, long seq ) {
35 |
36 | long madeId = -1;
37 | if (time == -1 || seq == -1)
38 | throw new IllegalArgumentException( "Both time and seq are required." );
39 | else if (version == -1) {
40 | if (type == -1) {
41 | if (genMethod == -1) {
42 | if (machine == -1) {
43 | madeId = idService.makeId(time, seq);
44 | } else {
45 | madeId = idService.makeId(machine, time, seq);
46 | }
47 | } else {
48 | madeId = idService.makeId(genMethod, machine, time, seq);
49 | }
50 | } else {
51 | madeId = idService.makeId(type, genMethod, machine, time, seq);
52 | }
53 | } else {
54 | madeId = idService.makeId(version, type, genMethod, time,
55 | seq, machine);
56 | }
57 |
58 | return madeId;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/springbt_vesta/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=8883
--------------------------------------------------------------------------------
/springbt_vesta/src/main/resources/ext/vesta/vesta-rest-main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
9 |
10 |
11 |
12 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/springbt_vesta/src/main/resources/ext/vesta/vesta-rest.properties:
--------------------------------------------------------------------------------
1 | vesta.machine=1021
2 | vesta.genMethod=2
3 | vesta.type=1
--------------------------------------------------------------------------------
/springbt_vesta/src/test/java/cn/codesheep/springbt_vesta/SpringbtVestaApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_vesta;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtVestaApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_vesta/vesta-intf-0.0.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springbt_vesta/vesta-intf-0.0.1.jar
--------------------------------------------------------------------------------
/springbt_vesta/vesta-service-0.0.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springbt_vesta/vesta-service-0.0.1.jar
--------------------------------------------------------------------------------
/springbt_watermark/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | cn.codesheep
7 | springbt_watermark
8 | 0.0.1
9 | jar
10 |
11 | springbt_watermark
12 | springbt_watermark
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 2.0.6.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-starter-test
36 | test
37 |
38 |
39 |
40 | commons-io
41 | commons-io
42 | 2.5
43 |
44 |
45 |
46 |
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-maven-plugin
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/SpringbtWatermarkApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringbtWatermarkApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringbtWatermarkApplication.class, args);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/comm/Const.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark.comm;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | import java.awt.*;
6 |
7 | @Component
8 | public class Const {
9 |
10 | public static final String LOGO_FILE_NAME = "codesheep_logo.png"; // 水印图片文件名
11 | public static final int X = 10; // 水印添加位置 X轴
12 | public static final int Y = 10; // 水印添加位置 Y轴
13 | public static final float ALPHA = 0.3F; // 水印透明度
14 | public static final int X_INTERVAL = 100; // 水印之间的间隔
15 | public static final int Y_INTERVAL = 150;
16 | }
17 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/controller/WatermarkController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark.controller;
2 |
3 | import cn.codesheep.springbt_watermark.model.dto.ImageInfo;
4 | import cn.codesheep.springbt_watermark.service.ImageUploadService;
5 | import cn.codesheep.springbt_watermark.service.WatermarkService;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.web.bind.annotation.*;
8 | import org.springframework.web.multipart.MultipartFile;
9 |
10 | import java.io.File;
11 |
12 | @RestController
13 | public class WatermarkController {
14 |
15 | @Autowired
16 | private ImageUploadService imageUploadService;
17 |
18 | @Autowired
19 | private WatermarkService watermarkService;
20 |
21 | @RequestMapping(value = "/watermarktest", method = RequestMethod.POST)
22 | public ImageInfo watermarkTest( @RequestParam("file") MultipartFile image ) {
23 |
24 | ImageInfo imgInfo = new ImageInfo();
25 |
26 | String uploadPath = "static/images/"; // 服务器上上传文件的相对路径
27 | String physicalUploadPath = getClass().getClassLoader().getResource(uploadPath).getPath(); // 服务器上上传文件的物理路径
28 |
29 | String imageURL = imageUploadService.uploadImage( image, uploadPath, physicalUploadPath );
30 | File imageFile = new File(physicalUploadPath + image.getOriginalFilename() );
31 |
32 | String watermarkAddImageURL = watermarkService.watermarkAdd(imageFile, image.getOriginalFilename(), uploadPath, physicalUploadPath);
33 |
34 | imgInfo.setImageUrl(imageURL);
35 | imgInfo.setLogoImageUrl(watermarkAddImageURL);
36 | return imgInfo;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/model/dto/ImageInfo.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark.model.dto;
2 |
3 | public class ImageInfo {
4 |
5 | private String imageUrl; // 上传文件的 URL相对地址
6 | private String logoImageUrl; // 添加了水印后的文件的 URL相对地址
7 |
8 | public String getImageUrl() {
9 | return imageUrl;
10 | }
11 |
12 | public void setImageUrl(String imageUrl) {
13 | this.imageUrl = imageUrl;
14 | }
15 |
16 | public String getLogoImageUrl() {
17 | return logoImageUrl;
18 | }
19 |
20 | public void setLogoImageUrl(String logoImageUrl) {
21 | this.logoImageUrl = logoImageUrl;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/service/ImageUploadService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark.service;
2 |
3 | import org.apache.commons.io.FileUtils;
4 | import org.springframework.stereotype.Service;
5 | import org.springframework.web.multipart.MultipartFile;
6 |
7 | import java.io.File;
8 | import java.io.IOException;
9 |
10 | @Service
11 | public class ImageUploadService {
12 |
13 | /**
14 | * 功能:上传图片
15 | * @param file 文件
16 | * @param uploadPath 服务器上上传文件的路径
17 | * @param physicalUploadPath 服务器上上传文件的物理路径
18 | * @return 上传文件的 URL相对地址
19 | */
20 | public String uploadImage( MultipartFile file, String uploadPath, String physicalUploadPath ) {
21 |
22 | String filePath = physicalUploadPath + file.getOriginalFilename();
23 |
24 | try {
25 | File targetFile=new File(filePath);
26 | FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
27 | } catch (IOException e) {
28 | e.printStackTrace();
29 | }
30 | return uploadPath + "/" + file.getOriginalFilename();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/service/WatermarkService.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark.service;
2 |
3 | import java.io.File;
4 |
5 | public interface WatermarkService {
6 |
7 | /**
8 | * 功能:给上传的图片添加水印
9 | *
10 | * @param imageFile 待添加水印的文件
11 | * @param imageFileName 文件名称
12 | * @param uploadPath 文件在服务器上的相对路径
13 | * @param realUploadPath 文件在服务器上的物理路径
14 | * @return 添加水印后的文件的地址
15 | */
16 | String watermarkAdd( File imageFile, String imageFileName, String uploadPath, String realUploadPath );
17 | }
18 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/java/cn/codesheep/springbt_watermark/service/impl/ImgWatermarkServiceImpl.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark.service.impl;
2 |
3 | import cn.codesheep.springbt_watermark.comm.Const;
4 | import cn.codesheep.springbt_watermark.service.WatermarkService;
5 | import com.sun.image.codec.jpeg.JPEGCodec;
6 | import com.sun.image.codec.jpeg.JPEGImageEncoder;
7 | import org.springframework.stereotype.Service;
8 |
9 | import javax.imageio.ImageIO;
10 | import java.awt.*;
11 | import java.awt.image.BufferedImage;
12 | import java.io.File;
13 | import java.io.FileOutputStream;
14 | import java.io.IOException;
15 | import java.io.OutputStream;
16 |
17 | @Service
18 | public class ImgWatermarkServiceImpl implements WatermarkService {
19 |
20 | @Override
21 | public String watermarkAdd( File imageFile, String imageFileName, String uploadPath, String realUploadPath ) {
22 |
23 | String logoFileName = "watermark_" + imageFileName;
24 | OutputStream os = null;
25 |
26 | try {
27 | Image image = ImageIO.read(imageFile);
28 |
29 | int width = image.getWidth(null);
30 | int height = image.getHeight(null);
31 |
32 | BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); // 创建图片缓存对象
33 | Graphics2D g = bufferedImage.createGraphics(); // 创建绘绘图工具对象
34 | g.drawImage(image, 0, 0, width,height,null); // 使用绘图工具将原图绘制到缓存图片对象
35 |
36 | String logoPath = realUploadPath + "/" + Const.LOGO_FILE_NAME; // 水印图片地址
37 | File logo = new File(logoPath); // 读取水印图片
38 | Image imageLogo = ImageIO.read(logo);
39 |
40 | int markWidth = imageLogo.getWidth(null); // 水印图片的宽度和高度
41 | int markHeight = imageLogo.getHeight(null);
42 |
43 | g.setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, Const.ALPHA) ); // 设置水印透明度
44 | g.rotate(Math.toRadians(-10), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2); // 旋转图片
45 |
46 | int x = Const.X;
47 | int y = Const.Y;
48 |
49 | int xInterval = Const.X_INTERVAL;
50 | int yInterval = Const.Y_INTERVAL;
51 |
52 | double count = 1.5;
53 | while ( x < width*count ) { // 循环添加水印
54 | y = -height / 2;
55 | while( y < height*count ) {
56 | g.drawImage(imageLogo, x, y, null); // 添加水印
57 | y += markHeight + yInterval;
58 | }
59 | x += markWidth + xInterval;
60 | }
61 |
62 | g.dispose();
63 |
64 | os = new FileOutputStream(realUploadPath + "/" + logoFileName);
65 | JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
66 | en.encode(bufferedImage);
67 |
68 | } catch (Exception e) {
69 | e.printStackTrace();
70 | } finally {
71 | if(os!=null){
72 | try {
73 | os.close();
74 | } catch (IOException e) {
75 | e.printStackTrace();
76 | }
77 | }
78 | }
79 |
80 | return uploadPath + "/" + logoFileName;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/springbt_watermark/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=9999
--------------------------------------------------------------------------------
/springbt_watermark/src/main/resources/static/images/codesheep_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/springbt_watermark/src/main/resources/static/images/codesheep_logo.png
--------------------------------------------------------------------------------
/springbt_watermark/src/test/java/cn/codesheep/springbt_watermark/SpringbtWatermarkApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.springbt_watermark;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class SpringbtWatermarkApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/test-id-spring-boot-starter/.DS_Store
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/id-spring-boot-starter-1.0.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/test-id-spring-boot-starter/id-spring-boot-starter-1.0.0.jar
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.1.7.RELEASE
9 |
10 |
11 | cn.codesheep
12 | test-id-spring-boot-starter
13 | 0.0.1-SNAPSHOT
14 | test-id-spring-boot-starter
15 | Demo project for Spring Boot
16 |
17 |
18 | 1.8
19 |
20 |
21 |
22 |
23 | org.springframework.boot
24 | spring-boot-starter-web
25 |
26 |
27 |
28 | org.springframework.boot
29 | spring-boot-starter-test
30 | test
31 |
32 |
33 |
34 | org.mybatis.spring.boot
35 | mybatis-spring-boot-starter
36 | 1.3.2
37 |
38 |
39 |
40 | com.alibaba
41 | druid-spring-boot-starter
42 | 1.1.9
43 |
44 |
45 |
46 | mysql
47 | mysql-connector-java
48 | runtime
49 |
50 |
51 |
52 |
53 | commons-collections
54 | commons-collections
55 | 3.2.2
56 |
57 |
58 |
59 | commons-lang
60 | commons-lang
61 | 2.6
62 |
63 |
64 |
65 | cn.codesheep
66 | id-spring-boot-starter
67 | 1.0.0
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 | org.springframework.boot
77 | spring-boot-maven-plugin
78 |
79 |
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/test-id-spring-boot-starter/src/.DS_Store
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/main/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hansonwang99/Spring-Boot-In-Action/807fd37643aa774b94fd004cc3adbd29ca17e9aa/test-id-spring-boot-starter/src/main/.DS_Store
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/main/java/cn/codesheep/testidspringbootstarter/TestIdSpringBootStarterApplication.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.testidspringbootstarter;
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({"org.zjs.cms","com.baidu.fsg.uid.worker.dao"})
9 | public class TestIdSpringBootStarterApplication {
10 |
11 | public static void main(String[] args) {
12 | SpringApplication.run(TestIdSpringBootStarterApplication.class, args);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/main/java/cn/codesheep/testidspringbootstarter/controller/TestController.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.testidspringbootstarter.controller;
2 |
3 |
4 | import com.baidu.fsg.uid.service.UidGenService;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.web.bind.annotation.GetMapping;
7 | import org.springframework.web.bind.annotation.RestController;
8 |
9 | @RestController
10 | public class TestController {
11 |
12 | @Autowired
13 | private UidGenService uidGenService;
14 |
15 | @GetMapping("/uid")
16 | public String genUid() {
17 |
18 | return String.valueOf(uidGenService.getUid());
19 | }
20 |
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/main/resources/application-dev.yml:
--------------------------------------------------------------------------------
1 | server:
2 | port: 8088
3 |
4 | spring:
5 | datasource:
6 | name: dataSource
7 | type: com.alibaba.druid.pool.DruidDataSource
8 | druid:
9 | name: dataSource
10 | url: jdbc:mysql://XXX.XXX.XXX.XXX:3306/demo?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useOldAliasMetadataBehavior=true&connectionCollation=utf8mb4_unicode_ci&rewriteBatchedStatements=true&allowMultiQueries=true
11 | username: XXXXXX
12 | password: XXXXXX
13 | driver-class-name: com.mysql.jdbc.Driver
14 | filters: stat,wall
15 | maxActive: 20
16 | initialSize: 1
17 | maxWait: 60000
18 | minIdle: 1
19 | timeBetweenEvictionRunsMillis: 60000
20 | minEvictableIdleTimeMillis: 300000
21 | validationQuery: select 'x'
22 | testWhileIdle: true
23 | testOnBorrow: false
24 | testOnReturn: false
25 | poolPreparedStatements: true
26 | maxOpenPreparedStatements: 20
27 | connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;druid.stat.logSlowSql=true
28 | filter:
29 | stat:
30 | enabled: true
31 | db-type: mysql
32 | merge-sql: true
33 | log-slow-sql: true
34 | slow-sql-millis: 2000
35 |
36 | mybatis:
37 | mapper-locations: classpath:mapper/*.xml
38 | configuration:
39 | log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | profiles:
3 | active: dev
4 |
5 |
6 |
--------------------------------------------------------------------------------
/test-id-spring-boot-starter/src/test/java/cn/codesheep/testidspringbootstarter/TestIdSpringBootStarterApplicationTests.java:
--------------------------------------------------------------------------------
1 | package cn.codesheep.testidspringbootstarter;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class TestIdSpringBootStarterApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------