Jedis
1.
引入依赖:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
测试类:
public class JedisConnTest { //使用jedis操作String 类型 @Test public void testString() { Jedis jedis = new Jedis("192.168.53.177", 6379); jedis.set("alias", "lisi"); String result = jedis.get("alias"); System.out.println(result); jedis.close(); } // 使用jedis操作map类型 @Test public void testMap() { Jedis jedis = new Jedis("192.168.53.177", 6379); jedis.hset("user", "name", "zhangsan"); jedis.hset("user", "age", "12"); String name = jedis.hget("user", "name"); String age = jedis.hget("user", "age"); System.out.println(name + "-" + age); jedis.close(); } // 使用连接池的jedis @Test public void testJedisPool() { JedisPool pool = new JedisPool("192.168.53.177", 6379); Jedis jedis = pool.getResource(); jedis.hset("cat","color","yellow"); System.out.println(jedis.hget("cat", "color")); } }
结果亲测有效( 注意关闭centos防火墙)
2. 由此可见spring只需要配置bean, spring版本的:
最简版 -当然这不科学:
<bean id="redis" class="redis.clients.jedis.Jedis" > <constructor-arg name="host" value="192.168.53.177" /> <constructor-arg name="port" value="6379" /> </bean>
连接池:
<bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <!-- 连接池配置 --> <constructor-arg name="poolConfig" ref="poolConfig" /> <constructor-arg name="host" value="192.168.53.177" /> <constructor-arg name="port" value="6379" /> </bean> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大连接数 --> <property name="maxTotal" value="30" /> <!-- 最大空闲连接数 --> <property name="maxIdle" value="10"/> <!-- 连接耗尽是否阻塞 --> <property name="blockWhenExhausted" value="true"/> </bean>
测试连接池:
@Controller public class FirstController { @Autowired JedisPool pool; @RequestMapping("/first") @ResponseBody public String first() { Jedis jedis = pool.getResource(); jedis.set("hobby", "sleep"); String result = jedis.get("hobby"); System.out.println(result); return "ok"; } }