0
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import redis.clients.jedis.*;
public class Welcome extends HttpServlet
{
Jedis jedis;

public void init(ServletConfig sc) throws ServletException
{

        Jedis jedis = new Jedis("localhost");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException
{
int count=0;
PrintWriter out=response.getWriter();
jedis.set("k1","123");//This statement is not working
}
public void destroy(){}
}

I have been trying to access keys and it's values in redis using jedis. It works fine with normal java code. but when it comes to servlets it's not working. I can't able to find the reasons. Pls answer me in detail that how can i use jedis.set() in servlets.

Karthikeyan Gopall
  • 5,469
  • 2
  • 19
  • 35
  • 1
    You aren't setting the instance variable `jedis`. The `init` callback is instantiating `Jedis` and assigning it to a local variable, not the instance variable. Change `Jedis jedis = new Jedis("localhost");` to `jedis = new Jedis("localhost");` or `this.jedis = new Jedis("localhost");` to be clearer – c.P.u1 Feb 16 '15 at 11:01

1 Answers1

0

Even so, We should not use Jedis object as an instance variable, because of thread safety. Instead of this, We use connection object in ServletContext by implementing ContextListener or resource injection. I think that we always consider thread safety when using Servlet instance. A single Jedis instance is not threadsafe! or; use JedisPool. it is thread safe.

JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");

Erdal76t
  • 113
  • 1
  • 9