로컬에서 중복 없는 uuid 생성 v4
1. JavaScript 브라우저 (모던)
1
2
3
4
5
6
7
8
9
10
// 네이티브 API (가장 권장)
const uuid = crypto.randomUUID();
console.log(uuid); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// Web Crypto API 사용
const array = new Uint8Array(16);
crypto.getRandomValues(array);
const uuid = ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
Node.js
1
2
3
4
5
6
7
8
9
10
11
12
// crypto 모듈 (Node.js 15.6.0+)
import { randomUUID } from 'crypto';
const uuid = randomUUID();
// uuid 패키지 (가장 일반적)
import { v4 as uuidv4 } from 'uuid';
const uuid = uuidv4();
// 다른 버전들
import { v1, v3, v5, v7 } from 'uuid';
const uuidv1 = v1(); // MAC 주소 + 타임스탬프
const uuidv7 = v7(); // 타임스탬프 기반 (최신)
설치
1
npm install uuid
2. Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import uuid
# UUID4 (랜덤) - 가장 일반적
uuid4 = str(uuid.uuid4())
print(uuid4) # "f47ac10b-58cc-4372-a567-0e02b2c3d479"
# 하이픈 없는 버전
uuid_no_dash = str(uuid.uuid4()).replace('-', '')
# 다른 버전들
uuid1 = str(uuid.uuid1()) # MAC + 타임스탬프
uuid3 = str(uuid.uuid3(uuid.NAMESPACE_DNS, 'example.com')) # MD5 해시
uuid5 = str(uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')) # SHA-1 해시
# UUID 객체로 작업
uuid_obj = uuid.uuid4()
print(uuid_obj.hex) # 하이픈 없는 hex
print(uuid_obj.bytes) # 바이트 형태
print(uuid_obj.version) # 4
커스텀 생성기
1
2
3
4
5
6
7
8
9
10
11
12
13
import uuid
import time
class UUIDGenerator:
@staticmethod
def generate():
return str(uuid.uuid4())
@staticmethod
def generate_with_timestamp():
timestamp = int(time.time() * 1000)
uuid_part = str(uuid.uuid4()).replace('-', '')[:16]
return f"{timestamp}_{uuid_part}"
3. C# (.NET)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
// 기본 GUID 생성
string uuid = Guid.NewGuid().ToString();
// "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// 다양한 형식
Guid guid = Guid.NewGuid();
string format1 = guid.ToString(); // 하이픈 포함
string format2 = guid.ToString("N"); // 하이픈 없음
string format3 = guid.ToString("D"); // 기본 (하이픈 포함)
string format4 = guid.ToString("B"); // 중괄호 포함
string format5 = guid.ToString("P"); // 괄호 포함
// 바이트 배열로 변환
byte[] bytes = guid.ToByteArray();
// 문자열에서 GUID 생성
Guid parsed = Guid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479");
bool success = Guid.TryParse("invalid", out Guid result);
커스텀 생성기
1
2
3
4
5
6
7
8
9
public static class UuidGenerator
{
public static string Generate() => Guid.NewGuid().ToString();
public static string GenerateShort() => Guid.NewGuid().ToString("N")[..8];
public static string GenerateWithPrefix(string prefix)
=> $"{prefix}_{Guid.NewGuid()}";
}
4. Unity (C#)
1
2
3
4
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
48
49
50
51
52
53
using System;
using UnityEngine;
public class UnityUUIDGenerator : MonoBehaviour
{
void Start()
{
// 기본 생성
string uuid = Guid.NewGuid().ToString();
Debug.Log($"UUID: {uuid}");
}
// 게임 오브젝트용 ID 생성
public static string GenerateGameObjectID()
{
return $"GO_{Guid.NewGuid().ToString("N")[..12]}";
}
// 플레이어 세션 ID
public static string GenerateSessionID()
{
var deviceId = SystemInfo.deviceUniqueIdentifier[..8];
var timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var randomPart = Guid.NewGuid().ToString("N")[..8];
return $"SESSION_{deviceId}_{timestamp}_{randomPart}";
}
}
// 컴포넌트로 자동 ID 할당
public class UniqueEntity : MonoBehaviour
{
[SerializeField] private string entityId;
public string EntityId => entityId;
private void Awake()
{
if (string.IsNullOrEmpty(entityId))
{
entityId = Guid.NewGuid().ToString();
}
}
#if UNITY_EDITOR
[ContextMenu("Regenerate ID")]
private void RegenerateId()
{
entityId = Guid.NewGuid().ToString();
UnityEditor.EditorUtility.SetDirty(this);
}
#endif
}
5. Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.UUID;
public class UuidGenerator {
// 기본 UUID 생성
public static String generateUuid() {
return UUID.randomUUID().toString();
}
// 하이픈 없는 버전
public static String generateUuidWithoutDashes() {
return UUID.randomUUID().toString().replace("-", "");
}
// 대문자 버전
public static String generateUppercaseUuid() {
return UUID.randomUUID().toString().toUpperCase();
}
// 바이트에서 생성
public static UUID generateFromBytes(byte[] bytes) {
// bytes는 16바이트여야 함
return UUID.nameUUIDFromBytes(bytes);
}
}
Android에서 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Android Activity에서
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 디바이스 정보와 함께
String deviceId = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.ANDROID_ID
);
String sessionId = UUID.randomUUID().toString();
String uniqueId = deviceId + "_" + sessionId;
Log.d("UUID", "Generated: " + uniqueId);
}
}
1
2
3
4
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
import java.nio.ByteBuffer;
import java.security.SecureRandom;
public class AdvancedUuidGenerator {
private static final SecureRandom random = new SecureRandom();
// 커스텀 UUID 생성
public static UUID generateCustomUuid() {
byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);
// UUID version 4 설정
randomBytes[6] &= 0x0f; /* clear version */
randomBytes[6] |= 0x40; /* set to version 4 */
randomBytes[8] &= 0x3f; /* clear variant */
randomBytes[8] |= 0x80; /* set to IETF variant */
ByteBuffer bb = ByteBuffer.wrap(randomBytes);
long firstLong = bb.getLong();
long secondLong = bb.getLong();
return new UUID(firstLong, secondLong);
}
// 타임스탬프 기반
public static String generateTimestampUuid() {
long timestamp = System.currentTimeMillis();
String uuid = UUID.randomUUID().toString().replace("-", "");
return timestamp + "_" + uuid.substring(0, 16);
}
}
- 다중 기기: 중복 없음
- 다중 스레드: 중복 없음
- 대규모: 수십억 개 생성해도 안전
- 크로스 플랫폼: 서버에 모아져도 중복 없음
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.