一、需求
solr安装完成以后,只要知道url就可以访问到solr后台,显然这很不安全,那么需求就是在访问的时候需要输入密码验证。
二、配置
1、修改部署solr的Tomcat的tomcat-users.xml
<!--
NOTE: The sample user and role entries below are intended for use with the
examples web application. They are wrapped in a comment and thus are ignored
when reading this file. If you wish to configure these users for use with the
examples web application, do not forget to remove the <!.. ..> that surrounds
them. You will also need to set the passwords to something appropriate.
-->
<!--
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
<user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
<user username="role1" password="<must-be-changed>" roles="role1"/>
-->
<!--添加用户名和密码-->
<role rolename="solr"/>
<user username="admin" password="admin" roles="solr"/>
</tomcat-users>
2、修改 WEB-INF/web.xml 在<webapp>节点内增加如下内容
<security-constraint>
<web-resource-collection>
<web-resource-name>Solr Lockdown</web-resource-name>
<url-pattern>/</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description>This applies only to the "tomcat" security role</description>
<role-name>solr</role-name>
<role-name>admin</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Solr</realm-name>
</login-config>
3、重启Tomcat ,访问就会要求输入用户名密码,输入上面设置的账号密码然后就可以登录。但是还有一个问题,页面加上密码,程序代码中就访问不到了,报HTTP/1.1 401 Unauthorized这个错误。下面解决这个问题只需要你修改一下链接即可
@Test
public void testQuery() throws SolrServerException{//过滤查询
//修改此处链接
//SolrServer solrServer=new HttpSolrServer("http://192.168.220.121:8080/solr/mycore");
SolrServer solrServer=new HttpSolrServer("http://admin:admin@192.168.139.129:8080/solr/mycore");
SolrQuery query=new SolrQuery();
query.set("q", "*:*");
String [] fq={"item_cat_id:2"};
query.addFilterQuery(fq); //过滤
QueryResponse result = solrServer.query(query);
SolrDocumentList results = result.getResults();
for (SolrDocument list:results){
String str1 = list.get("item_gid").toString();
String str2=list.get("item_title").toString();
System.out.println("分类gid-----"+str1);
System.out.println("商品名称-----"+str2);
}
}