用enum枚举类实现单例模式

用enum枚举类实现单例模式:

public enum FastDFSClient {
    instances;
    private StorageClient1 storageClient1 = null;
    private Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    FastDFSClient() {
        TrackerClient tracker = new TrackerClient();
        StorageServer storageServer = null;
        TrackerServer trackerServer = null;
        while (true) {
            try {
                trackerServer = tracker.getConnection();
                storageServer = tracker.getStoreStorage(trackerServer);
                break;
            } catch (IOException e) {
                logger.error("create fastDFS fail retry");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e1) {
                    logger.warn("thread interrupt");
                }
            }
        }
        this.storageClient1 = new StorageClient1(trackerServer, storageServer);
    }

    public void init(Map<String, String> map) throws Exception {
        Properties initPropertie = new Properties();
        //只需要设置ip, 其余的使用默认值即可
        initPropertie.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS, map.get(BrowserConstants.FASTDFS_SERVERS));
        ClientGlobal.initByProperties(initPropertie);
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = tracker.getConnection();
        if (!ProtoCommon.activeTest(trackerServer.getSocket())) {
            throw new Exception("无法连接到fastDFS");
        }
    }

    public String uploadFile(byte[] contents) {
        try {
            return storageClient1.upload_file1(contents, null, null);
        } catch (Exception e) {
            logger.error("fastDFS save error", e);
            return null;
        }
    }

    public int deleteFile(String file_id) throws Exception {
        try {
            return storageClient1.delete_file1(file_id);
        } catch (Exception e) {
            logger.error("fastDFS delete error.", e);
            return 0;
        }
    }

    public int truncateFile(String appender_file_id) {
        try {
            return storageClient1.truncate_file1(appender_file_id);
        } catch (Exception e) {
            logger.error("fastDFS truncate error", e);
            return 0;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值