spingboot第三方util形式整合ehcache

ehcache的各种原理,应用都不介绍了,官网里有,其他博客一大堆。您可以快速查阅,这篇博客纯属笔记。

开始使用要在application.java的开始代码中添加@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class Application

在application.yml中添加cache内容

spring:
  cache:
    type: ehcache
    ehcache:
        config: classpath:ehcache.xml

pom引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.8.3</version>
</dependency>

注解形式使用cache

//查询缓存
@Cacheable(value = "album_search", key = "#type")
public List<String>countStory(String type)

//刷新清除所有缓存
@CacheEvict(value = "album_search", allEntries = true)
public void clearHotSongCache() {}

代码中的value是ehchache.xml中的name

<cache name= "album_search"
           maxElementsInMemory= "1000"
           eternal= "false"
           timeToIdleSeconds= "180"
           timeToLiveSeconds= "86400"
           overflowToDisk= "false" />

整个的ehcache.xml配置
xml中的各种属性,不会的可以百度;着重注意一下是eternal,如果是false就是这个内存是定时的,timeToIdleSeconds, timeToLiveSeconds才会有用。

<ehcache>
    <diskStore path ="java.io.tmpdir"/>
    <defaultCache maxElementsInMemory= "10000"
                   eternal= "false"
                   timeToIdleSeconds= "120"
                   timeToLiveSeconds= "120"
                   overflowToDisk= "true"
                   diskSpoolBufferSizeMB= "30"
                   maxElementsOnDisk= "1000000"
                   diskPersistent= "false"
                   diskExpiryThreadIntervalSeconds="120"
                   memoryStoreEvictionPolicy= "LRU"  />

    <cache name= "album_search"
           maxElementsInMemory= "1000"
           eternal= "false"
           timeToIdleSeconds= "180"
           timeToLiveSeconds= "86400"
           overflowToDisk= "false" />
</ehcache>

第三方cacheutil代码

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * <p>description: ehcache缓存工具类
 *    ALBUM_SEARCH是配置在ehcache.xml中的cacheName
 * </p>
 *
 * @author chenrui
 * @since 2018-07-17
 */
public class QQAlbumEhcacheUtil {

    private static CacheManager cacheManager = CacheManager.create();

    private static final String ALBUM_SEARCH = "album_search";

    public static Object get(Object key) {
        Cache cache = cacheManager.getCache(ALBUM_SEARCH);
        if(cache!= null) {
            Element element = cache.get(key);
            if(element != null) {
                return element.getObjectValue();
            }
        }
        return null;
    }

    public static void put(Object key, Object value) {
        Cache cache = cacheManager.getCache(ALBUM_SEARCH);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }

    public static boolean remove(Object key) {
        Cache cache = cacheManager.getCache(ALBUM_SEARCH);
        if (cache != null) {
            return cache.remove(key);
        }
        return false;
    }

    public static void main(String[] args) {
        String key = "key";
        String value = "hello";
        QQAlbumEhcacheUtil.put(key, value);
        QQAlbumEhcacheUtil.get(key);
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot中使用HttpClient调用第三方HTTPS接口,并忽略SSL证书验证,可以通过以下步骤来实现: 1. 导入HttpClient和SSL相关的依赖: 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>javax.net.ssl</groupId> <artifactId>javax.net.ssl.HttpsURLConnection</artifactId> <version>1.0.0</version> </dependency> ``` 2. 创建忽略SSL验证的HttpClient对象: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HttpClientUtil { public HttpClient createIgnoreSSLHttpClient() throws Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } }; sslContext.init(null, new TrustManager[]{trustManager}, null); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(120 * 1000).setConnectTimeout(120 * 1000).build(); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setDefaultRequestConfig(reqConfig).build(); return httpClient; } } ``` 3. 使用创建的HttpClient对象发送HTTPS请求: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; public class HttpsClientExample { public static void main(String[] args) throws Exception { HttpClientUtil httpClientUtil = new HttpClientUtil(); CloseableHttpClient httpClient = (CloseableHttpClient) httpClientUtil.createIgnoreSSLHttpClient(); HttpGet httpGet = new HttpGet("https://example.com/api"); CloseableHttpResponse response = httpClient.execute(httpGet); String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(responseBody); response.close(); httpClient.close(); } } ``` 以上就是使用Spring Boot中的HttpClient实现忽略SSL证书的步骤。总结起来,主要包括导入相关依赖,创建忽略SSL验证的HttpClient对象,以及使用该对象发送HTTPS请求。 ### 回答2: Spring Boot中使用HttpClient调用第三方HTTPS接口时,如果忽略SSL证书验证,可以按照以下方法进行操作。 首先,需要在Spring Boot的配置文件application.properties中添加以下配置: ```plaintext # 忽略SSL证书验证 spring.main.allow-bean-definition-overriding=true ``` 然后,创建一个自定义的HttpClientConfig类,用于配置并创建HttpClient对象: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.net.ssl.SSLContext; @Configuration public class HttpClientConfig { @Value("${httpclient.ssl.ignore-ssl}") private boolean ignoreSSL; @Bean @ConditionalOnProperty(name = "httpclient.ssl.ignore-ssl", havingValue = "true") public HttpClient httpClient() throws Exception { if (ignoreSSL) { SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial((chain, authType) -> true) .build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); return HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .setDefaultRequestConfig(requestConfig()) .build(); } else { return HttpClients.createDefault(); } } private RequestConfig requestConfig() { return RequestConfig.custom() .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); } } ``` 最后,在需要调用第三方HTTPS接口的地方注入HttpClient对象,并使用该对象进行接口调用即可: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class HttpService { @Autowired private HttpClient httpClient; public String getResponse(String url) throws Exception { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); return EntityUtils.toString(httpResponse.getEntity()); } } ``` 以上就是使用Spring Boot的HttpClient调用第三方HTTPS接口并忽略SSL证书验证的方法。请注意,忽略SSL证书验证可能存在安全风险,建议在生产环境中谨慎使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值