/* * Copyright 1999-2015 dangdang.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package com.dangdang.ddframe.rdb.sharding.id.generator.self; import com.dangdang.ddframe.rdb.sharding.id.generator.IdGenerator; import java.net.InetAddress; import java.net.UnknownHostException; /** * 根据机器IP获取工作进程Id,如果线上机器的IP二进制表示的最后10位不重复,建议使用此种方式 * ,列如机器的IP为192.168.1.108,二进制表示:11000000 10101000 00000001 01101100 * ,截取最后10位 01 01101100,转为十进制364,设置workerId为364. * * @author DonneyYoung */ public class IPIdGenerator implements IdGenerator { private final CommonSelfIdGenerator commonSelfIdGenerator = new CommonSelfIdGenerator(); static { initWorkerId(); } static void initWorkerId() { InetAddress address; try { address = InetAddress.getLocalHost(); } catch (final UnknownHostException e) { throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!"); } byte[] ipAddressByteArray = address.getAddress(); CommonSelfIdGenerator.setWorkerId((long) (((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF))); } @Override public Number generateId() { return commonSelfIdGenerator.generateId(); } }