1.ID唯一生成器
- UUID生成唯一标识
-
- 不建议、没有顺序,并且特别占用空间
- 雪花算法(项目使用)
-
- 有序,只有数字
- 不好处依赖于时间
- Redis
-
- 自增
-
-
- String、Hash、Zset
-
雪花算法介绍
- 后台生成SessionId需要保证全局唯一,我们可借鉴SnowFlake(雪花算法)来实现;
- 什么是雪花算法?
-
- 雪花算法是Twitter公司内部为分布式环境下生成唯一ID的一种算法解决方案,底层会帮助我们生成一个64位(比特位)的long类型的Id;
- 雪花算法是Twitter公司内部为分布式环境下生成唯一ID的一种算法解决方案,底层会帮助我们生成一个64位(比特位)的long类型的Id;
机器id和服务id说明
2.能干什么?(能解决什么问题?)
对项目多个实例或分布式项目生成全局唯一ID值,保证ID唯一性。
3.如何使用
各种开发语言都有对雪花算法的实现,我们直接在stock_common工程中引入已写好的工具类即可:
package com.itheima.stock.utils;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* 分布式自增长ID实现,底层基于Twitter的Snowflake
* 64位ID (42(时间戳)+5(机房ID)+5(机器ID)+12(序列号-同毫秒内重复累加))
* @author itheima
*/
public class IdWorker {
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private final static long twepoch = 1288834974657L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生产id时间戳 */
private static long lastTimestamp = -1L;
//同毫秒并发控制
private long sequence = 0L;
//机器ID
private final long workerId;
//机房ID
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作机器ID
* @param datacenterId
* 序列号
*/
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
/**
* 获取下一个ID
*
* @return
*/
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* <p>
* 获取 maxWorkerId
* </p>
*/
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
/*
* GET jvmPid
*/
mpid.append(name.split("@")[0]);
}
/*
* MAC + PID 的 hashcode 获取16个低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
}
PS:如果项目中使用MybatisPlus,自带雪花算法,不需要引入上面的类。
在stock_backend 的 application.yml 配置文件中添加配置:
jrzs:
idwork:
dataCenterId: 1 #指定数据中心
workerId: 1 #指定工作机器
在stock_backend工程配置ID生成器bean对象:
package com.itheima.stock.config;
import com.itheima.stock.utils.IdWorker;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* <p></p>
*
* @Description:
*/
@Data
@Component
@ConfigurationProperties(prefix = "jrzs.idwork")
public class IdWorkerConfig {
private Long dataCenterId;
private Long workerId;
/**
* 配置id生成器bean
* @return
*/
@Bean
public IdWorker idWorker(){
//基于运维人员对机房和机器的编号规划自行约定
return new IdWorker(dataCenterId,workerId);
}
}
2.Redis 应用
1.是什么?
非关系型数据库,效率高。将数据保存内存中。
2.能干什么?(能解决什么问题?)
3.如何使用?
在 Linux 的 docker 中构建 redis 容器,如下命令:
docker run -dit --privileged=true -p 6379:6379 --restart=always -v /usr/soft/redis/conf/redis.conf:/etc/redis/redis.conf -v /usr/soft/redis/data:/data --name redis redis:6.0 --requirepass "itcast"
在stock_backend工程引入redis相关依赖:
<!--redis场景依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis创建连接池,默认不会创建连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
定义application.yml文件专门配置缓存信息:
spring:
# 配置缓存
redis:
host: 192.168.200.129
port: 6379
database: 0 #Redis数据库索引(默认为0)
lettuce:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 1 # 连接池中的最小空闲连接
timeout: PT10S # 连接超时时间
password: itcast
自定义RedisTemplate序列化:
@Configuration
public class RedisCacheConfig {
/**
* 配置redisTemplate bean,自定义数据的序列化的方式
* @param redisConnectionFactory 连接redis的工厂,底层有场景依赖启动时,自动加载
* @return
*/
@Bean
public RedisTemplate redisTemplate(@Autowired RedisConnectionFactory redisConnectionFactory){
//1.构建RedisTemplate模板对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//2.为不同的数据结构设置不同的序列化方案
//设置key序列化方式
template.setKeySerializer(new StringRedisSerializer());
//设置value序列化方式
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
//设置hash中field字段序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
//设置hash中value的序列化方式
template.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
//5.初始化参数设置
template.afterPropertiesSet();
return template;
}
}
测试redis基础环境:
package com.itheima.stock;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
/**
* @author by itheima
* @Date 2021/12/30
* @Description
*/
@SpringBootTest
public class TestRedis {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void test01(){
//存入值
redisTemplate.opsForValue().set("myname","zhangsan");
//获取值
String myname = redisTemplate.opsForValue().get("myname");
System.out.println(myname);
}
String 类型
// 将 key 中储存的数字值增加 1
redisTemplate.opsForValue().increment(key, 1L);
// 将 key 中储存的数字值减少 1
redisTemplate.opsForValue().increment(key, -1L);
// hash自增
redisTemplate.opsForHash().increment("大key", "小key", -1);
redisTemplate.opsForHash().increment("大key", "小key", 1);
// Zset自增
redisTemplate.opsForZSet().incrementScore("key","value",-1);
redisTemplate.opsForZSet().incrementScore("key","value",1);
}
3.后端验证码生成器
1.是什么?
可以在后端生产验证码信息:字母、文字、数字。
2.能干什么?(能解决什么问题?)
为前端生成验证图片信息
说明:前端图片验证码以base64数据格式展示(点击图片查看源码):
<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAAoCAYAAADXGucZAAAEoElEQVR42u2cWWhUVxjHfZBSoUV8qAihT4Xii7Y1BIptKRQE8dkHN2yhi0JE02SapUUU4zJZjKZWEtNJYkJ2kpjUzNyZO5OZyUxW40iCCOJDCwpiSzeUWqttv8535Z650+SOE9tS7jf/hx935txzXmb4neU73znLotEomTyz17Mo1joAAOexLJtKdh0AOgUABIm+FNABAJADogMAIDoAAKIDACA6AACiAwAgOgAQ3cTrj1F14zQVHU3Qrk/maYdr3ngWH0vQyaZp0gJjon6AP08sV+TSH3+r5HkFRFiIb91+hTjR