首页 文章 精选 留言 我的

精选列表

搜索[分布式SQL],共10000篇文章
优秀的个人博客,低调大师

分布式缓存系统

一、缓存条目与淘汰策略 ``` # distributed_cache/models.py import time import os import json import hashlib import threading from enum import Enum from typing import Any, Dict, List, Optional, Tuple from dataclasses import dataclass, field, asdict from collections import OrderedDict class EvictionPolicy(Enum): 16051.h.kuaisou.com LRU = "lru" # Least Recently Used LFU = "lfu" # Least Frequently Used FIFO = "fifo" # First In First Out TTL = "ttl" # Time To Live only @dataclass class CacheEntry: 16052.h.kuaisou.com """A single cached item.""" key: str value: Any created_at: float = 0.0 last_accessed_at: float = 0.0 access_count: int = 0 ttl_seconds: float = 0.0 # 0 = no expiry expires_at: float = 0.0 size_bytes: int = 0 tags: List[str] = field(default_factory=list) version: int = 1 dirty: bool = False # modified but not persisted def __post_init__(self): 16053.h.kuaisou.com now = time.time() if self.created_at == 0: 16054.h.kuaisou.com self.created_at = now if self.last_accessed_at == 0: 16055.h.kuaisou.com self.last_accessed_at = now if self.ttl_seconds > 0: 16056.h.kuaisou.com self.expires_at = self.created_at + self.ttl_seconds if self.size_bytes == 0: 16057.h.kuaisou.com self.size_bytes = self._estimate_size() def _estimate_size(self) -> int: 16058.h.kuaisou.com try: 16060.h.kuaisou.com return len(json.dumps(self.value, default=str).encode()) except Exception: 16059.h.kuaisou.com return len(str(self.value).encode()) def is_expired(self) -> bool: 16061.h.kuaisou.com if self.ttl_seconds self.expires_at def touch(self) -> None: 16063.h.kuaisou.com self.last_accessed_at = time.time(16064.h.kuaisou.com) self.access_count += 1 def to_dict(self) -> Dict[str, Any]: 17001.h.kuaisou.com return asdict(self) @classmethod def from_dict(cls, data: Dict[str, Any]) -> "CacheEntry": 17002.h.kuaisou.com return cls(**data) class LRUCache: 17003.h.kuaisou.com """LRU eviction using OrderedDict.""" def __init__(self, max_size_bytes: int = 100 * 1024 * 1024): 17004.h.kuaisou.com self.max_size_bytes = max_size_bytes self._cache: OrderedDict[str, CacheEntry] = OrderedDict(17005.h.kuaisou.com) self._current_size = 0 self._lock = threading.RLock(17006.h.kuaisou.com) def get(self, key: str) -> Optional[CacheEntry]: 17007.h.kuaisou.com with self._lock: 17008.h.kuaisou.com entry = self._cache.get(key) if entry is None: 17009.h.kuaisou.com return None if entry.is_expired(): 17010.h.kuaisou.com self._remove(key) return None self._cache.move_to_end(key) entry.touch(17011.h.kuaisou.com) return entry def put(self, entry: CacheEntry) -> Optional[CacheEntry]: 17012.h.kuaisou.com with self._lock: 17013.h.kuaisou.com evicted = None if entry.key in self._cache: 17014.h.kuaisou.com old = self._cache[entry.key] self._current_size -= old.size_bytes self._remove(entry.key) while self._current_size + entry.size_bytes > self.max_size_bytes and self._cache: evicted_key, evicted_entry = self._cache.popitem(last=False) self._current_size -= evicted_entry.size_bytes evicted = evicted_entry self._cache[entry.key] = entry self._current_size += entry.size_bytes return evicted def remove(self, key: str) -> Optional[CacheEntry]: 17015.h.kuaisou.com with self._lock: return self._remove(key) def _remove(self, key: str) -> Optional[CacheEntry]: 17016.h.kuaisou.com entry = self._cache.pop(key, None) if entry: 17017.h.kuaisou.com self._current_size -= entry.size_bytes return entry def keys(self) -> List[str]: 17018.h.kuaisou.com with self._lock: 17019.h.kuaisou.com return list(self._cache.keys()) def size(self) -> int: 17020.h.kuaisou.com with self._lock: 17021.h.kuaisou.com return len(self._cache) def current_bytes(self) -> int: 17022.h.kuaisou.com with self._lock: 17023.h.kuaisou.com return self._current_size def clear(self) -> None: 17024.h.kuaisou.com with self._lock: 17025.h.kuaisou.com self._cache.clear(17026.h.kuaisou.com) self._current_size = 0 class LFUCache: 17117.h.kuaisou.com """LFU eviction with frequency counter.""" def __init__(self, max_size_bytes: int = 100 * 1024 * 1024): 17121.h.kuaisou.com self.max_size_bytes = max_size_bytes self._cache: Dict[str, CacheEntry] = {} self._freq_map: Dict[int, OrderedDict[str, CacheEntry]] = {} self._min_freq = 0 self._current_size = 0 self._lock = threading.RLock(17122.h.kuaisou.com) def get(self, key: str) -> Optional[CacheEntry]: 17129.h.kuaisou.com with self._lock: 17135.h.kuaisou.com entry = self._cache.get(key) if entry is None: 17137.h.kuaisou.com return None if entry.is_expired(): 17147.h.kuaisou.com self._remove(key) return None self._update_freq(entry) return entry def put(self, entry: CacheEntry) -> Optional[CacheEntry]: 17148.h.kuaisou.com with self._lock: 17152.h.kuaisou.com evicted = None if entry.key in self._cache: 17153.h.kuaisou.com old = self._cache[entry.key] self._current_size -= old.size_bytes self._remove(entry.key) while self._current_size + entry.size_bytes > self.max_size_bytes and self._cache: 17157.h.kuaisou.com evicted = self._evict_lfu(17154.h.kuaisou.com) self._cache[entry.key] = entry self._current_size += entry.size_bytes freq = entry.access_count if freq not in self._freq_map: 17162.h.kuaisou.com self._freq_map[freq] = OrderedDict(17168.h.kuaisou.com) self._freq_map[freq][entry.key] = entry self._min_freq = min(self._min_freq, freq) if self._min_freq else freq return evicted def _update_freq(self, entry: CacheEntry) -> None: 17171.h.kuaisou.com old_freq = entry.access_count entry.touch() new_freq = entry.access_count if old_freq in self._freq_map: 17177.h.kuaisou.com self._freq_map[old_freq].pop(entry.key, None) if not self._freq_map[old_freq]: 17175.h.kuaisou.com del self._freq_map[old_freq] if self._min_freq == old_freq: 17174.h.kuaisou.com self._min_freq += 1 if new_freq not in self._freq_map: 17178.h.kuaisou.com self._freq_map[new_freq] = OrderedDict(17173.h.kuaisou.com) self._freq_map[new_freq][entry.key] = entry def _evict_lfu(self) -> Optional[CacheEntry]: 17180.h.kuaisou.com if not self._cache: 17179.h.kuaisou.com return None freq = self._min_freq while freq not in self._freq_map or not self._freq_map[freq]: 17184.h.kuaisou.com freq += 1 if freq > 100000: 17183.h.kuaisou.com break self._min_freq = freq if freq in self._freq_map and self._freq_map[freq]: 17186.h.kuaisou.com evict_key, evict_entry = self._freq_map[freq].popitem(last=False) if not self._freq_map[freq]: 17187.h.kuaisou.com del self._freq_map[freq] self._cache.pop(evict_key, None) self._current_size -= evict_entry.size_bytes return evict_entry return None def _remove(self, key: str) -> Optional[CacheEntry]: 17188.h.kuaisou.com entry = self._cache.pop(key, None) if entry: freq = entry.access_count if freq in self._freq_map: 17189.h.kuaisou.com self._freq_map[freq].pop(key, None) if not self._freq_map[freq]: 17190.h.kuaisou.com del self._freq_map[freq] self._current_size -= entry.size_bytes return entry def remove(self, key: str) -> Optional[CacheEntry]: 17191.h.kuaisou.com with self._lock: 17192.h.kuaisou.com return self._remove(key) def keys(self) -> List[str]: 17193.h.kuaisou.com with self._lock: 17194.h.kuaisou.com return list(self._cache.keys(17197.h.kuaisou.com)) def size(self) -> int: 17207.h.kuaisou.com with self._lock: 22016.h.kuaisou.com return len(self._cache) def current_bytes(self) -> int: 22021.h.kuaisou.com with self._lock: 1103113.h.kuaisou.com return self._current_size def clear(self) -> None: 1103114.h.kuaisou.com with self._lock: 1103116.h.kuaisou.com self._cache.clear(1103117.h.kuaisou.com) self._freq_map.clear(1103118.h.kuaisou.com) self._min_freq = 0 self._current_size = 0 ``` --- ### 二、一致性哈希与分片 ``` # distributed_cache/sharding.py import hashlib import bisect import threading from typing import Dict, List, Optional, Tuple class ConsistentHash: 1103122.h.kuaisou.com """Consistent hashing with virtual nodes.""" def __init__(self, num_virtual_nodes: int = 150): 1103123.h.kuaisou.com self.num_virtual_nodes = num_virtual_nodes self._ring: Dict[int, str] = {} self._sorted_keys: List[int] = [] self._nodes: set = set(1103124.h.kuaisou.com) self._lock = threading.RLock(1103271.h.kuaisou.com) def _hash(self, key: str) -> int: 1103272.h.kuaisou.com return int(hashlib.md5(key.encode()).hexdigest(), 16) def add_node(self, node_id: str) -> None: 1103273.h.kuaisou.com with self._lock: 1103274.h.kuaisou.com if node_id in self._nodes: 1103275.h.kuaisou.com return self._nodes.add(node_id) for i in range(self.num_virtual_nodes): 1103277.h.kuaisou.com virtual_key = f"{node_id}:vn{i}" h = self._hash(virtual_key) self._ring[h] = node_id bisect.insort(self._sorted_keys, h) def remove_node(self, node_id: str) -> None: 1103278.h.kuaisou.com with self._lock: 1103279.h.kuaisou.com if node_id not in self._nodes: 1103280.h.kuaisou.com return self._nodes.discard(node_id) for i in range(self.num_virtual_nodes): 1103281.h.kuaisou.com virtual_key = f"{node_id}:vn{i}" h = self._hash(virtual_key) self._ring.pop(h, None) idx = bisect.bisect_left(self._sorted_keys, h) if idx Optional[str]: 1103283.h.kuaisou.com with self._lock: 1103284.h.kuaisou.com if not self._sorted_keys: 1103285.h.kuaisou.com return None h = self._hash(key) idx = bisect.bisect_right(self._sorted_keys, h) if idx >= len(self._sorted_keys): 1103288.h.kuaisou.com idx = 0 return self._ring[self._sorted_keys[idx]] def get_nodes(self, key: str, count: int = 3) -> List[str]: 1103292.h.kuaisou.com """Get multiple candidate nodes for replication.""" with self._lock: 1103297.h.kuaisou.com if not self._sorted_keys: 1103293.h.kuaisou.com return [] h = self._hash(key) idx = bisect.bisect_right(self._sorted_keys, h) nodes = [] seen = set(1103298.h.kuaisou.com) for _ in range(len(self._sorted_keys)): 1103299.h.kuaisou.com if idx >= len(self._sorted_keys): 1103300.h.kuaisou.com idx = 0 node = self._ring[self._sorted_keys[idx]] if node not in seen: 1103302.h.kuaisou.com nodes.append(node) seen.add(node) if len(nodes) >= count: 1103303.h.kuaisou.com break idx += 1 return nodes def get_all_nodes(self) -> List[str]: 1103304.h.kuaisou.com with self._lock: 1103306.h.kuaisou.com return list(self._nodes) def node_count(self) -> int: 1103305.h.kuaisou.com with self._lock: 1103307.h.kuaisou.com return len(self._nodes) class ShardManager: 1103309.h.kuaisou.com """Manages cache shards across nodes.""" def __init__(self, num_virtual_nodes: int = 150): 1103310.h.kuaisou.com self.hash_ring = ConsistentHash(num_virtual_nodes) self._shards: Dict[str, "LocalCacheShard"] = {} self._lock = threading.RLock(1103312.h.kuaisou.com) def add_shard(self, node_id: str, shard: "LocalCacheShard") -> None: 1103313.h.kuaisou.com with self._lock: 1103314.h.kuaisou.com self.hash_ring.add_node(node_id) self._shards[node_id] = shard def remove_shard(self, node_id: str) -> Optional["LocalCacheShard"]: 1103315.h.kuaisou.com with self._lock: 1103316.h.kuaisou.com self.hash_ring.remove_node(node_id) return self._shards.pop(node_id, None) def get_shard_for_key(self, key: str) -> Optional["LocalCacheShard"]: 1103317.h.kuaisou.com node_id = self.hash_ring.get_node(key) if node_id is None: 1103318.h.kuaisou.com return None return self._shards.get(node_id) def get_replica_shards(self, key: str, count: int = 2) -> List["LocalCacheShard"]: 1103319.h.kuaisou.com node_ids = self.hash_ring.get_nodes(key, count + 1) shards = [] for nid in node_ids: 1103320.h.kuaisou.com shard = self._shards.get(nid) if shard: 1103321.h.kuaisou.com shards.append(shard) return shards def get_all_shards(self) -> List[Tuple[str, "LocalCacheShard"]]: 1104101.h.kuaisou.com with self._lock: 1103322.h.kuaisou.com return list(self._shards.items()) def redistribute_keys(self) -> Dict[str, List[str]]: 1104102.h.kuaisou.com """Return migration plan: source_node -> [keys to move].""" plan: Dict[str, List[str]] = {} for node_id, shard in self._shards.items(): 1104104.h.kuaisou.com for key in shard.keys(): 1104105.h.kuaisou.com target_node = self.hash_ring.get_node(key) if target_node and target_node != node_id: 1104109.h.kuaisou.com plan.setdefault(node_id, []).append(key) return plan ``` --- ### 三、本地缓存分片与多级缓存 ``` # distributed_cache/cache.py import os import json import time import threading import logging from typing import Any, Dict, List, Optional, Set, Callable from distributed_cache.models import ( CacheEntry, EvictionPolicy, LRUCache, LFUCache ) from distributed_cache.sharding import ShardManager logger = logging.getLogger(__name__) class LocalCacheShard: 1104110.h.kuaisou.com """Thread-safe local cache shard with eviction and expiry.""" def __init__( self, max_size_bytes: int = 100 * 1024 * 1024, policy: EvictionPolicy = EvictionPolicy.LRU, cleanup_interval: float = 30.0, ): self.max_size_bytes = max_size_bytes self.policy = policy self.cleanup_interval = cleanup_interval if policy == EvictionPolicy.LFU: 1104112.h.kuaisou.com self._store = LFUCache(max_size_bytes) else: 1104111.h.kuaisou.com self._store = LRUCache(max_size_bytes) self._lock = threading.RLock(1104113.h.kuaisou.com) self._tags: Dict[str, Set[str]] = {} # tag -> set of keys self._running = False self._cleanup_thread: Optional[threading.Thread] = None self._stats = { "hits": 0, "misses": 0, "puts": 0, "evictions": 0, "expirations": 0, "deletes": 0, } def start(self) -> None: 1104114.h.kuaisou.com self._running = True self._cleanup_thread = threading.Thread( target=self._cleanup_loop, daemon=True, name="cache-cleanup" ) self._cleanup_thread.start(1104115.h.kuaisou.com) def stop(self) -> None: 1104116.h.kuaisou.com self._running = False if self._cleanup_thread: 1104117.h.kuaisou.com self._cleanup_thread.join(timeout=5) def get(self, key: str) -> Optional[Any]: 1104118.h.kuaisou.com with self._lock: 1104123.h.kuaisou.com entry = self._store.get(key) if entry is None: 1104124.h.kuaisou.com self._stats["misses"] += 1 return None self._stats["hits"] += 1 return entry.value def put( self, key: str, value: Any, ttl_seconds: float = 0, tags: Optional[List[str]] = None, ) -> Optional[CacheEntry]: 1107102.h.kuaisou.com with self._lock: 1107104.h.kuaisou.com entry = CacheEntry( key=key, value=value, ttl_seconds=ttl_seconds, tags=tags or [], ) evicted = self._store.put(entry) self._stats["puts"] += 1 if evicted: 1107105.h.kuaisou.com self._stats["evictions"] += 1 self._remove_tags(evicted.key) if entry.tags: 1107106.h.kuaisou.com for tag in entry.tags: 1107125.h.kuaisou.com self._tags.setdefault(tag, set()).add(key) return evicted def delete(self, key: str) -> bool: 1107126.h.kuaisou.com with self._lock: 1107127.h.kuaisou.com entry = self._store.remove(key) if entry: 1107129.h.kuaisou.com self._stats["deletes"] += 1 self._remove_tags(key) return True return False def exists(self, key: str) -> bool: 1107130.h.kuaisou.com with self._lock: 1107131.h.kuaisou.com return self._store.get(key) is not None def ttl(self, key: str) -> float: 1107132.h.kuaisou.com with self._lock: 1107134.h.kuaisou.com entry = self._store.get(key) if entry is None: 1107135.h.kuaisou.com return -1 if entry.ttl_seconds List[str]: 1107143.h.kuaisou.com with self._lock: 1107144.h.kuaisou.com return self._store.keys(1107148.h.kuaisou.com) def size(self) -> int: 1107156.h.kuaisou.com with self._lock: 1107155.h.kuaisou.com return self._store.size(1107157.h.kuaisou.com) def current_bytes(self) -> int: 1107158.h.kuaisou.com with self._lock: return self._store.current_bytes(1107159.h.kuaisou.com) def clear(self) -> None: 1107160.h.kuaisou.com with self._lock: 1107163.h.kuaisou.com self._store.clear(1107167.h.kuaisou.com) self._tags.clear(1107168.h.kuaisou.com) def invalidate_by_tag(self, tag: str) -> int: 1107170.h.kuaisou.com with self._lock: 1107171.h.kuaisou.com keys = self._tags.pop(tag, set()) count = 0 for key in keys: 1107172.h.kuaisou.comv if self._store.remove(key): 1107173.h.kuaisou.com count += 1 return count def get_stats(self) -> Dict[str, Any]: 1107174.h.kuaisou.com with self._lock: 1107175.h.kuaisou.com total = self._stats["hits"] + self._stats["misses"] hit_rate = self._stats["hits"] / total if total > 0 else 0 return { **self._stats, "hit_rate": round(hit_rate, 4), "entries": self._store.size(1107176.h.kuaisou.com), "bytes_used": self._store.current_bytes(1107177.h.kuaisou.com), "max_bytes": self.max_size_bytes, } def _remove_tags(self, key: str) -> None: 1107178.h.kuaisou.com for tag, key_set in list(self._tags.items()): 1107179.h.kuaisou.com key_set.discard(key) if not key_set: 1107180.h.kuaisou.com del self._tags[tag] def _cleanup_loop(self) -> None: 1107181.h.kuaisou.com while self._running: 1107182.h.kuaisou.com time.sleep(self.cleanup_interval) self._cleanup_expired(1107183.h.kuaisou.com) def _cleanup_expired(self) -> None: 1107184.h.kuaisou.com with self._lock: 1108106.h.kuaisou.com now = time.time(1108107.h.kuaisou.com) expired_keys = [] for key in self._store.keys(1108109.h.kuaisou.com): 1108108.h.kuaisou.com entry = self._store.get(key) if entry and entry.is_expired(): 1108110.h.kuaisou.com expired_keys.append(key) for key in expired_keys: 1108112.h.kuaisou.com self._store.remove(key) self._stats["expirations"] += 1 self._remove_tags(key) if expired_keys: 1108113.h.kuaisou.com logger.info("Cleaned up %d expired entries", len(expired_keys)) class MultiLevelCache: 1108114.h.kuaisou.com """L1 (memory) + L2 (disk) + L3 (remote) cache.""" def __init__( self, l1_max_bytes: int = 100 * 1024 * 1024, l2_dir: str = "/tmp/cache_l2", l2_max_bytes: int = 1 * 1024 * 1024 * 1024, remote_fetcher: Optional[Callable[[str], Optional[Any]]] = None, ): self.l1 = LocalCacheShard(max_size_bytes=l1_max_bytes) self.l2_dir = l2_dir self.l2_max_bytes = l2_max_bytes self.remote_fetcher = remote_fetcher self._lock = threading.RLock(1108115.h.kuaisou.com) self._pending: Dict[str, threading.Event] = {} os.makedirs(l2_dir, exist_ok=True) self.l1.start(1108116.h.kuaisou.com) def get(self, key: str) -> Optional[Any]: 1108117.h.kuaisou.com # L1 val = self.l1.get(key) if val is not None: 1108118.h.kuaisou.com return val # L2 val = self._l2_get(key) if val is not None: 1108119.h.kuaisou.com self.l1.put(key, val) return val # L3 / remote if self.remote_fetcher: 1108120.h.kuaisou.com # cache-aside with single-flight val = self._single_flight(key) if val is not None: 1108121.h.kuaisou.com self.l1.put(key, val) self._l2_put(key, val) return val return None def put( self, key: str, value: Any, ttl_seconds: 1108122.h.kuaisou.com ```

优秀的个人博客,低调大师

hadoo分布式安装

前骤: Hadoop Cluster中的Daemon HDFS: NameNode,NN SecondaryNode,SNN DataNode:DN /data/hadoop/hdfs/{nn,snn,dn} nn:fsimage,editlog//镜像和编辑日志 //hdfs的NN是在内存中存放数据,不断根据文件状态改变,修改元数据 fsimage存放了:文件分割后存放在哪些node上 //文件元数据的改变,会写入到editllog中,最后写入到fsimage中,因此下次NN重启后数据依然存在,从fsimage中读取数据,获取到内存中 //一旦nn崩溃,数据恢复需要大量的时间 snn:在nn崩溃的时候,及时顶上去,省去修复nn,让nn重新上线的时间,但是各个data node报告数据状态,进行修复的时间依然需要。 正常情况下:snn负责copy nn的fsimage和editlog然后在snn上合并 checkpoint:因为nn是在不断变化的,因此snn要指定合并到那个时间点上。 //官方建议30个以上的node构建hadoop集群 data是否需要工作于raid//因为hdfs已经有replicate的功能,因此再次提供冗余的必要性不大 hadoop-daemon.sh 运行进程 在集群模式中hadoop-daemon.sh start DataNode时,需要自动的找每一个DataNode节点,然后在每一个DataNode上自动启动。 如何找到,或者如何保证命令能够通过主控节点,自动连接到各从节点,并且有权限执行命令。 在主节点上:配置 YARN: ResourceManager NodeManager: yarn-daemon.sh start/stop 实际运行进程: 【NN】 【SNN】 【RM】 | | | --------------------------------- [node1/NN] [nod2/NN] [node3/NN] 在node上启动:datanode进程和nodemanager进程即可 实验模型: 【NN/SNN/RM】 | ----------------------------------------- [node1/NN] [nod2/NN] [node3/NN] 主控节点上运行:namenode,secondarynamenode,resourcemanager三个进程 其他node上启动:datanode进程和nodemanager进程 预备: 1.ntpdate 同步 tzselect, timedatactl //查看时区设置 timedatectl list-timezones # 列出所有时区 timedatectl set-local-rtc 1 # 将硬件时钟调整为与本地时钟一致, 0 为设置为 UTC 时间 timedatectl set-timezone Asia/Shanghai # 设置系统时区为上海 cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime //最简单的方案 2.hosts通信 172.16.100.67 node1.mt.com node1 master 172.16.100.68 node2.mt.com node2 172.16.100.69 node3.mt.com node3 172.16.100.70 node4.mt.com node4 如果需要通过master节点启动或停止整个集群,需要在master上配置运行服务的用户,如hdfs和yarn能够基于密钥ssh链接 node1: 一、前奏 (1)配置环境 vim /etc/profile.d/java.sh JAVA_HOME=/usr yum install java-1.8.0-openjdk-devel.x86_64 scp /etc/profile.d/java.sh node2:/etc/profile.d/ scp /etc/profile.d/java.sh node3:/etc/profile.d/ scp /etc/profile.d/java.sh node4:/etc/profile.d/ vim /etc/profile.d/hadoop.sh export HADOOP_PREFIX=/bdapps/hadoop export PATH=$PATH:${HADOOP_PREFIX}/bin:${HADOOP_PREFIX}/sbin export HADOOP_YARN_HOME=${HADOOP_PREFIX} export HADOOP_MAPPERD_HOME=${HADOOP_PREFIX} export HADOOP_COMMON_HOME=${HADOOP_PREFIX} export HADOOP_HDFS_HOME=${HADOOP_PREFIX} . /etc/profile.d/hadoop.sh scp /etc/profile.d/hadoop.sh node2:/etc/profile.d/ scp /etc/profile.d/hadoop.sh node3:/etc/profile.d/ scp /etc/profile.d/hadoop.sh node4:/etc/profile.d/ (2)修改hosts文件 vim /etc/hosts 172.16.100.67 node1.mt.com node1 master 172.16.100.68 node2.mt.com node2 172.16.100.69 node3.mt.com node3 172.16.100.70 node4.mt.com node4 scp 到 node2,node3,node4 (3)hadoop 密钥登录 useradd hadoop //node2,3,4都有一个hadoop用户 echo "hadoop" | passwd --stdin hadoop useradd -g hadoop hadoop //这里都使用一个用户,也可以分别创建yarn和hdfs用户 su - hadoop ssh-keygen for i in 2 3 4; do ssh-copy-id -i .ssh/id_rsa.pub hadoop@node${i}; done 验证: ssh node2 'date' ssh node3 'date' ssh node4 'date' 二、安装部署hadoop (1)解压 mkdir -pv /bdapps/ /data/hadoop/hdfs/{nn,snn,dn} //这里的dn是用不到的,因为主控节点是不存储数据的,可以不创建 chown -R hadoop:hadoop /data/hadoop/hdfs tar xvf hadoop-2.6.2.tar.gz -C /bdapps/ cd /bdapps/ ln -sv hadoop-2.6.2 hadoop cd hadoop mkdir logs chown g+w logs chown -R hadoop:hadoop ./* (2)配置文件修改 1.core-site.xml 配置 vim etc/hadoop/core-site.xml <configuration> <property> <name>fs.defaultFS</name> <value>hdfs://master:8020</value> //hdfs的访问接口,master如果不能解析,用ip地址也可以 <final>true</final> </property> </configuration> //core指向NN 2.yanr-site.xml文件配置 vim etc/hadoop/yarn-site.xml <configuration> <property> <name>yarn.resourcemanager.address</name> <value>master:8032</value> </property> <property> <name>yarn.resourcemanager.scheduler.address</name> <value>master:8030</value> </property> <property> <name>yarn.resourcemanager.resource-tracker.address</name> <value>master:8031</value> </property> <property> <name>yarn.resourcemanager.admin.address</name> <value>master:8033</value> </property> <property> <name>yarn.resourcemanager.webapp.address</name> <value>master:8088</value> </property> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> <property> <name>yarn.nodemanager.auxservices.mapreduce_shuffle.class</name> <value>org.apache.hadoop.mapred.ShuffleHandler</value> </property> <property> <name>yarn.resourcemanager.scheduler.class</name> <value>org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler</value> </property> </configuration> //%s/localhost/master/g //替换localhost为master //指向ResourceManager 3.hdfs-site.xml配置 vim etc/hadoop/hdfs-site.xml <configuration> <property> <name>dfs.replication</name> //dfs的副本数量 <value>2</value> </property> <proporty> <name>dfs.namenode.name.dir</name> <value>file:///data/hadoop/hdfs/nn</value> </property> <proporty> <name>dfs.datanode.data.dir</name> <value>file:///data/hadoop/hdfs/dn</value> </property> <property> <name>fs.checkpoint.dir</name> <value>file:///data/hadoop/hdfs/snn</value> </property> <property> <name>fs.checkpoint.edits.dir</name> <value>file:///data/hadoop/hdfs/snn</value> </property> </configuration> 4. mapred-site.xml 是唯一不需要修改的 默认的就是yarn就可以 5. vim slaves node2 node3 node4 //slaves是datanode和nodemanager (3) 在node2,node3,node4指定到该步骤后:chown -R hadoop:hadoop ./* su - hadoop scp /bdapps/hadoop/etc/hadoop/* node2:/bdapps/hadoop/etc/hadoop/ scp /bdapps/hadoop/etc/hadoop/* node3:/bdapps/hadoop/etc/hadoop/ scp /bdapps/hadoop/etc/hadoop/* node4:/bdapps/hadoop/etc/hadoop/ 三.格式化然后启动 su - hadoop hdfs namenode -format 显示/data/hadoop/hdfs/nn hash been successful formatted 表示成功 启动hadoop方式有两种: 1.在各节点上分别启动要启动的服务 启动yarn服务要使用yarn用户身份 master节点:NameNode服务和ResourceManager服务 su - hdfs -c 'hadoop-daemon.sh start namenode' su - hdfs -c 'yarn-daemon.sh start resourcemanager' slave节点:DataNode服务和NodeManager服务 su - hdfs -c 'hadoop-daemon.sh start datanode' su - hdfs -c 'yarn-daemon.sh start nodemanager' 2.在master上启动整个集群 su - hdfs -c 'start-dfs.sh' su - hdfs -c 'start-yarn.sh' 老版本通过start-all.sh和stop-all.sh来控制hdfs和mapreduce 启动服务: su - hdfs -c 'start-dfs.sh' su - hdfs -c 'stop-dfs.sh' //关闭hdfs 会提示在,2,3,4节点上启动 su - hdfs -c 'start-yarn.sh' master启动resourcemanager slave上启动nodemanager 测试: node3: su - hadoop jps //查看DataNode进程和NodeManager进程 node1:su - hadoop jps //启动的有secondaryNameNode和NameNode进程 hdfs dfs -mkdir /test hdfs dfs -put /etc/fstab /test/fstab hdfs dfs -ls -R /test hdfs dfs -cat /test/fstab node3: ls /data/hadoop/hdfs/dn/current/..../blk,... 存储在这里 注意:node2,3,4中有一个是没有存储该文件的,因为定义的slaves 为2个 vim etc/hadoop/hdfs-site.xml <name>dfs.replication</name> //dfs的副本数量 <value>2</value> Web接口查看: 172.16.100.67:8088 内存显示为24G,因为3G,每个node的物理内存代大小为8G 172.16.100.67:50070 datanode: 有三个 单个文件太小的是不会被切割的,大于64M的文件会被切片 可以直接上传压缩文件,会被切块 运行任务测试: yarn jar /bdapps/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-example-2.6.jar wordcount /test/fstab /test/functions /test/wc hdfs dfs cat /test/wc/part-r-0000 四、其他节点 node2: user hadoop echo "hadoop" | passwd --stdin hadoop mkdir -pv /bdapps /data/hadoop/hdfs/{nn,snn,dn} //只有dn有用 chown -R hadoop:hadoop /data/hadoop/hdfs/ tar xvf hadoop-2.6.2.tar.gz -C /bdapps/ cd /bdapps/ ln -sv hadoop-2.6.2 hadoop cd hadoop mkdir logs chown g+w logs chown -R hadoop:hadoop ./* //可以在修改配置文件后,直接复制到node3和node4上因为配置都一样 node3: user hadoop echo "hadoop" | passwd --stdin hadoop mkdir -pv /bdapps /data/hadoop/hdfs/{nn,snn,dn} //只有dn有用 chown -R hadoop:hadoop /data/hadoop/hdfs/ tar xvf hadoop-2.6.2.tar.gz -C /bdapps/ cd /bdapps/ ln -sv hadoop-2.6.2 hadoop cd hadoop mkdir logs chown g+w logs chown -R hadoop:hadoop ./* node4: user hadoop echo "hadoop" | passwd --stdin hadoop mkdir -pv /bdapps /data/hadoop/hdfs/{nn,snn,dn} //只有dn有用 chown -R hadoop:hadoop /data/hadoop/hdfs/ tar xvf hadoop-2.6.2.tar.gz -C /bdapps/ cd /bdapps/ ln -sv hadoop-2.6.2 hadoop cd hadoop mkdir logs chown g+w logs chown -R hadoop:hadoop ./* ===================================================== yarn的集群管理命令 yarn [--config confdir] COMMAND resourcemanager-format-state-store //删除RMStateStore resourcemanager //运行ResourceManager nodemanaer //运行nodemanager on each slave timelineserver //运行timelineserver,任务编排,时间线 rmadmin //resourcemanager管理 version jar //运行jar文件 application //显示application信息 report/kill application applicationattempt //尝试运行相关报告 container //容器相关信息 node //显示node queue //报告队列信息 logs //备份容器日志 classpath //显示java运行程序时的类加载路径 daemonlog //获取守护进程的日志级别 jar,application,node,logs,classpath,version 是常用的用户命令 resourcemanager,nodemanager,proxyserver,rmadmin,daemon是常用的管理类命令 yarn application [options] -status ApplicationID 状态信息 yarn application -status application_1494685700454_0001 -list 列出yarn上的application列表 -appTypes:MAPREDUCE,YARN -appStates:ALL,NEW,NEW_SAVING,SUBMITTED,ACCEPTED,RUNNING,FINISHED,FAILED,KILLED yarn application -appStates=all -kill ApplicationID yarn node -list //例出node列表 -states: NEW,RUNNING,UNHEALTHY不健康,DECOMMISSION退役的,LOST,REBOOTED -staus Node-ID //显示节点信息 logs:显示已经完成的YARN程序的日志(及状态为:FAILED,KILLED,FINISHED) 如果需要在命令行查看日志需要配置yarn-site.xml yarn.log-aggregation-enable 属性值为true yarn logs -applicationId [applicationID] [options] -applicationId applicationID必备选项,用于从ResourceManager获取其详细信息。 -appOwner APPOwner默认为当前用户,可选 -nodeAddress NodeAddress -containerId containerID:获取当前指定节点上指定容器的相关信息;其中NodeAddress的格式同NodeId classpath: yarn calasspath //加载java程序路径 管理命令: rmadmin nodemanager timelineserver rmadmin是ResourceManager的客户端程序,可用于刷新访问控制策略、调度器队列及注册到RM上的节点等。 刷新之后,无需重启即可生效。 yarn rmadmin [options] -help -refreshQueues:重载队列的acl,状态及调用器队列;它会根据配置文件中的配置信息重新初始化调度器 -refreshNodes:为RM刷新主机信息,它通过读取RM节点的include和exclude文件来更新集群需要包含或排除的节点列表。 -refreshUserToGroupMappings:根据配置的Hadoop安全组映射,通过刷新组缓存中的信息来更新用户和组之间的映射关系。 -refreshSuperUserGroupsConfiguration:刷新超级用户代理组映射,以及更新代理主机和core-site.xml配置文件中的hadoop.proxyuser属性定义的代理组 -refreshAdminAcls:根据yarn站点配置文件或默认配置文件的yarn.admin.acl属性刷新RM的管理ACL; -refreshServiceAcl:重载服务级别授权策略文件,而后RM将重载授权策略文件;它会检查hadoop安全授权是否启用并为IPC Server,ApplicationMaster,Client及Resource tracker刷新ACL; DaemonLog:查看或更细 http://host:port/logLevel?log=name service? yarn daemonlog [options] args -getLevel host:port name:显示指定守护进程的日志级别 -getLevel host:port level:设置守护进程的日志级别 运行YARN application yarn application可以是一个shell脚本,MapReduce作业或者其他类型的任意作业。 步骤: 1.Application初始化提交 //client端完成 2.分配内存并启动AM //RM完成 3.AM注册及资源分配 //AM在nodemanager上完成 4.启动并监控容器 //AM向NM报告,NM报告RM完成 5.Application进度报告 //AM完成 6.Application进度完成 // 利用ambari部署hadoop集群 https://www.ibm.com/developerworks/cn/opensource/os-cn-bigdata-ambari/ https://cwiki.apache.org/confluence/display/AMBARI/Installation+Guide+for+Ambari+2.5.0 IBM官方技术论坛:https://www.ibm.com/developerworks/cn/opensource/ Ambari 2.2.2 下载资源 OS Format URL http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.2.2.0 http://public-repo-1.hortonworks.com/ambari/centos6/2.x/updates/2.2.2.0/ambari.repo http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.2.2.0/ambari-2.2.2.0-centos7.tar.gz HDP 2.4.2 下载资源 http://public-repo-1.hortonworks.com/HDP/centos7/2.x/updates/2.4.2.0 http://public-repo-1.hortonworks.com/HDP/centos7/2.x/updates/2.4.2.0/hdp.repo http://public-repo-1.hortonworks.com/HDP/centos7/2.x/updates/2.4.2.0/HDP-2.4.2.0-centos7-rpm.tar.gz http://public-repo-1.hortonworks.com/HDP-UTILS-1.1.0.20/repos/centos7 http://public-repo-1.hortonworks.com/HDP-UTILS-1.1.0.20/repos/centos7/HDP-UTILS-1.1.0.20-centos7.tar.gz 本文转自MT_IT51CTO博客,原文链接:http://blog.51cto.com/hmtk520/1944156,如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码