spring boot基於1.x.java
一 集成redisredis
1.1 配置spring
spring.redis.host = localhost spring.redis.port = 6379 spring.redis.timeout = 10000 spring.redis.database = 0 spring.redis.pool.max-active = 100 spring.redis.pool.max-wait = -1 spring.redis.pool.max-idle = 8 spring.redis.pool.min-idle = 0
1.2 數據庫
工具類json
package com.test.util; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Component; /** * @ClassName:RedisTemplateUtil * @Description: redis工具類 * @author: * @date:2018-03-08 23:28:23 * */ @SuppressWarnings("unchecked") @Component public class RedisTemplateUtil { @SuppressWarnings("rawtypes") @Autowired private RedisTemplate redisTemplate; /** * 寫入緩存 * @param key * @param value * @return */ public boolean set(final String key, Object value, Integer database) { boolean result = false; try { JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(database); redisTemplate.setConnectionFactory(jedisConnectionFactory); ValueOperations<String, Object> operations = (ValueOperations<String, Object>) redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 寫入緩存設置時效時間 * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime, TimeUnit unit, Integer database) { boolean result = false; try { JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(database); redisTemplate.setConnectionFactory(jedisConnectionFactory); ValueOperations<String, Object> operations = redisTemplate.opsForValue(); operations.set(key, value, expireTime, unit); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 批量刪除對應的value * @param keys */ public void remove(Integer database, final String... keys) { for (String key : keys) { remove(database, key); } } /** * 批量刪除key * @param pattern */ public void removePattern(Integer database, final String pattern) { Set<String> keys = redisTemplate.keys(pattern); if (keys.size() > 0){ JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(database); redisTemplate.setConnectionFactory(jedisConnectionFactory); redisTemplate.delete(keys); } } /** * 刪除對應的value * @param key */ public void remove(Integer database, final String key) { if (exists(database, key)) { redisTemplate.delete(key); } } /** * 判斷緩存中是否有對應的value * @param key * @return */ public boolean exists(Integer database, final String key) { JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(database); redisTemplate.setConnectionFactory(jedisConnectionFactory); return redisTemplate.hasKey(key); } /** * 讀取緩存 * @param key * @return */ public Object get(Integer database, final String key) { Object result = null; JedisConnectionFactory jedisConnectionFactory = (JedisConnectionFactory) redisTemplate.getConnectionFactory(); jedisConnectionFactory.setDatabase(database); redisTemplate.setConnectionFactory(jedisConnectionFactory); ValueOperations<String, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } /** * 哈希 添加 * @param key * @param hashKey * @param value */ public void hmSet(String key, Object hashKey, Object value){ HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); hash.put(key,hashKey,value); } /** * 哈希獲取數據 * @param key * @param hashKey * @return */ public Object hmGet(String key, Object hashKey){ HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); return hash.get(key,hashKey); } /** * 列表添加 * @param k * @param v */ public void lPush(String k,Object v){ ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush(k,v); } /** * 列表獲取 * @param k * @param l * @param l1 * @return */ public List<Object> lRange(String k, long l, long l1){ ListOperations<String, Object> list = redisTemplate.opsForList(); return list.range(k,l,l1); } /** * 集合添加 * @param key * @param value */ public void add(String key,Object value){ SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add(key,value); } /** * 集合獲取 * @param key * @return */ public Set<Object> setMembers(String key){ SetOperations<String, Object> set = redisTemplate.opsForSet(); return set.members(key); } /** * 有序集合添加 * @param key * @param value * @param scoure */ public void zAdd(String key,Object value,double scoure){ ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add(key,value,scoure); } /** * 有序集合獲取 * @param key * @param scoure * @param scoure1 * @return */ public Set<Object> rangeByScore(String key,double scoure,double scoure1){ ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.rangeByScore(key, scoure, scoure1); } public void extentExpire(String key, Long expireTime, TimeUnit unit) { redisTemplate.boundValueOps(key).expire(expireTime, unit); } }
二 集成elasticsearch緩存
2.1 配置app
elasticsearch.ip=localhost elasticsearch.port=9300 elasticsearch.cluster.name=my-elasticsearch elasticsearch.pool=100 elasticsearch.index=test elasticsearch.type=test
2.2dom
package com.test.util; import java.util.Map; import java.util.UUID; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequestBuilder; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.transport.TransportClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSONObject; /** * ES的操做數據類 * * 備註:對es的一些操做作了一些封裝,抽出來一些操做,就是傳統的dao層,數據服務 * * * */ @Component public class ESRepository { private static final Logger log = LoggerFactory.getLogger(ESRepository.class); @Autowired private TransportClient client; /** * 建立索引 * * @param index * @return */ public boolean buildIndex(String index) { if (!isIndexExist(index)) { log.info("Index is not exits!"); } CreateIndexResponse buildIndexresponse = client.admin().indices().prepareCreate(index).execute().actionGet(); log.info(" 建立索引的標誌: " + buildIndexresponse.isAcknowledged()); return buildIndexresponse.isAcknowledged(); } /** * 刪除索引 * * @param index * @return */ public boolean deleteIndex(String index) { if (!isIndexExist(index)) { log.info(" 索引不存在 !!!!!!"); } DeleteIndexResponse diResponse = client.admin().indices().prepareDelete(index).execute().actionGet(); if (diResponse.isAcknowledged()) { log.info("刪除索引**成功** index->>>>>>>" + index); } else { log.info("刪除索引**失敗** index->>>>> " + index); } return diResponse.isAcknowledged(); } /** * 查詢數據 * @param index 索引<----->關係型數據庫 * @param type 類型<----->關係型數據表 * @param id 數據ID<----->id * @return */ public Map<String, Object> searchDataByParam(String index, String type, String id) { if(index == null || type == null || id == null) { log.info(" 沒法查詢數據,缺惟一值!!!!!!! "); return null; } //來獲取查詢數據信息 GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id); GetResponse getResponse = getRequestBuilder.execute().actionGet(); //這裏也有指定的時間獲取返回值的信息,若有特殊需求能夠 return getResponse.getSource(); } /** * 更新數據 * * @param data 添加的數據類型 json格式的 * @param index 索引<----->關係型數據庫 * @param type 類型<----->關係型數據表 * @param id 數據ID<----->id * @return */ public void updateDataById(JSONObject data, String index, String type, String id) { if(index == null || type == null || id == null) { log.info(" 沒法更新數據,缺惟一值!!!!!!! "); return; } //更新步驟 UpdateRequest up = new UpdateRequest(); up.index(index).type(type).id(id).doc(data); //獲取響應信息 //.actionGet(timeoutMillis),也能夠用這個方法,當過了必定的時間還沒獲得返回值的時候,就自動返回。 UpdateResponse response = client.update(up).actionGet(); log.info("更新數據狀態信息,status{}", response.status().getStatus()); } /** * 添加數據 * * @param data 添加的數據類型 json格式的 * @param index 索引<----->關係型數據庫 * @param type 類型<----->關係型數據表 * @param id 數據ID<----->id * @return */ public String addTargetDataALL(String data, String index, String type, String id) { //判斷一下次id是否爲空,爲空的話就設置一個id if(id == null) { id = UUID.randomUUID().toString(); } //正式添加數據進去 IndexResponse response = client.prepareIndex(index, type, id).setSource(data).get(); log.info("addTargetDataALL 添加數據的狀態:{}", response.status().getStatus()); return response.getId(); } /** * 經過ID刪除數據 * * @param index 索引,相似數據庫 * @param type 類型,相似表 * @param id 數據ID */ public void delDataById(String index, String type, String id) { if(index == null || type == null || id == null) { log.info(" 沒法刪除數據,缺惟一值!!!!!!! "); return; } //開始刪除數據 DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet(); log.info("刪除數據狀態,status-->>>>{},", response.status().getStatus()); } /** * 判斷索引是否存在 * * @param index * @return */ public boolean isIndexExist(String index) { IndicesExistsResponse iep = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet(); if (iep.isExists()) { log.info("此索引 [" + index + "] 已經在ES集羣裏存在"); } else { log.info(" 沒有此索引 [" + index + "] "); } return iep.isExists(); } }
三 集成fastdfselasticsearch
3.1ide
配置
fastdfs.minPoolSize=10 fastdfs.maxPoolSize=30 fastdfs.waitTimes=200 connect_timeout = 2 network_timeout = 30 charset = UTF-8 http.tracker_http_port = 8180 tracker_server = 10.20.8.252:22122
3.2
工具類
package com.test.comm; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * Title:ConnectionPool Copyright:Copyright(c)2018 Company:test * * @author * @date 2018年9月18日 下午3:15:50 */ @Component public class ConnectionPool { private final static Logger logger = LoggerFactory.getLogger(ConnectionPool.class); /** 空閒的鏈接池 */ private LinkedBlockingQueue<StorageClient1> idleConnectionPool = new LinkedBlockingQueue<StorageClient1>(); /** 鏈接池默認最小鏈接數 */ @Value("${fastdfs.minPoolSize}") private long minPoolSize; /** 鏈接池默認最大鏈接數 */ @Value("${fastdfs.maxPoolSize}") private long maxPoolSize; /** 默認等待時間(單位:秒) */ @Value("${fastdfs.waitTimes}") private long waitTimes; @Value("${spring.profiles.active}") private String profile; /** * @Description: 建立TrackerServer,並放入空閒鏈接池 */ public void createTrackerServer() { logger.debug("[建立TrackerServer(createTrackerServer)]"); TrackerServer trackerServer = null; try { initClientGlobal(); for (int i = 0; i < minPoolSize; i++) { // 把client1添加到鏈接池 StorageServer storageServer = null; StorageClient1 client1 = new StorageClient1(trackerServer, storageServer); idleConnectionPool.add(client1); } } catch (Exception e) { logger.error("[建立TrackerServer(createTrackerServer)][異常:{}]", e); } } /** * @Description: 獲取空閒鏈接 1).在空閒池(idleConnectionPool)中彈出一個鏈接; * 2).把該鏈接放入忙碌池(busyConnectionPool)中; 3).返回 connection * 4).若是沒有idle connection, 等待 wait_time秒, and check again * @throws AppException */ public StorageClient1 checkout() { StorageClient1 client1 = idleConnectionPool.poll(); if (client1 == null) { if (idleConnectionPool.size() < maxPoolSize) { createTrackerServer(); try { client1 = idleConnectionPool.poll(waitTimes, TimeUnit.SECONDS); } catch (Exception e) { logger.error("[獲取空閒鏈接(checkout)-error][error:獲取鏈接超時:{}]", e); } } } // 添加到忙碌鏈接池 // busyConnectionPool.put(client1, obj); logger.debug("[獲取空閒鏈接(checkout)][獲取空閒鏈接成功]"); return client1; } /** * @Description: 釋放繁忙鏈接 1.若是空閒池的鏈接小於最小鏈接值,就把當前鏈接放入idleConnectionPool; * 2.若是空閒池的鏈接等於或大於最小鏈接值,就把當前釋放鏈接丟棄; * @param client1 * 需釋放的鏈接對象 */ public void checkin(StorageClient1 client1) { logger.debug("[釋放當前鏈接(checkin)]"); client1 = null; if (idleConnectionPool.size() < minPoolSize) { createTrackerServer(); } } private void initClientGlobal() throws Exception { String FASTDFS_CONFIG = "application-" + profile + ".properties"; ClientGlobal.init(FASTDFS_CONFIG); } public LinkedBlockingQueue<StorageClient1> getIdleConnectionPool() { return idleConnectionPool; } public long getMinPoolSize() { return minPoolSize; } public void setMinPoolSize(long minPoolSize) { if (minPoolSize != 0) { this.minPoolSize = minPoolSize; } } public long getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(long maxPoolSize) { if (maxPoolSize != 0) { this.maxPoolSize = maxPoolSize; } } public long getWaitTimes() { return waitTimes; } public void setWaitTimes(int waitTimes) { if (waitTimes != 0) { this.waitTimes = waitTimes; } } }
四 集成rabbitmq
4.1 配置
spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=12345678 spring.rabbitmq.publisher-confirms=true spring.rabbitmq.virtual-host=/
4.2
package com.test.rabbitmq; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.context.annotation.Bean; /** * 在這裏新建一個隊列,並將隊列與交換機綁定 * * <p> * Title:Application * </p> * <p> * Description:TODO * </p> * <p> * Copyright:Copyright(c)2005 * </p> * <p> * Company:test * </p> * * @author * @date 2018年9月12日 上午9:40:48 */ public class Application { /** * 新建隊列 */ @Bean public Queue queuePush() { return new Queue("sy-admin-push"); } /** * 建立交換機 */ @Bean TopicExchange exchange() { return new TopicExchange("sy-exchange-admin"); } /** * 綁定交換機 */ /** * 將隊列topic.message與exchange綁定,binding_key爲topic.message,就是徹底匹配 * @param queueMessage * @param exchange * @return */ @Bean Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message"); } @Bean public void binding () { Queue queue = queuePush(); TopicExchange exchange = exchange(); bindingExchangeMessage(queue, exchange); } }
模擬消費者
package com.test.rabbitmq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import com.test.util.AESUtils; @Component @RabbitListener(queues = "test") public class Consumer { private final static Logger logger = LoggerFactory.getLogger(Consumer.class); @RabbitHandler public void process(String message) { logger.debug("模擬移動端接收到一條推送消息" + message); logger.debug("解密後的消息 " + AESUtils.decryptData(message)); } }
模擬生產者
package com.test.rabbitmq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.test.util.AESUtils; @Component public class Producer { private final static Logger logger = LoggerFactory.getLogger(Producer.class); @Autowired private RabbitTemplate rabbitTemplate; public void producer (final String queue, final String message) { new Thread(new Runnable() { @Override public void run() { logger.debug("接收到一條消息" + message); //加密 String newMessage = AESUtils.encryptData(message); logger.debug("加密後的消息爲 " + newMessage); rabbitTemplate.convertSendAndReceive(queue, newMessage); logger.debug("向移動端推送消息" + newMessage); } }).start(); } }